配置项:
@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 getUserAttribute(String userId) {
Keycloak kcMaster = Keycloak.getInstance(url, MASTER_REALM, adminUserName, adminPassword, clientId);
RealmResource realmResource = kcMaster.realm(TARGET_REALM);
UsersResource userResource = realmResource.users();
Map attributeMap = new HashMap<>();
List userList = userResource.list();
for (UserRepresentation user : userList) {
Map> 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
attributeMap.put("medicalInsitution", Arrays.asList(medicalInstitution));
attributeMap.put("telephone", Arrays.asList(telephone));
attributeMap.put("code", Arrays.asList(code));
attributeMap.put("userLevel", Arrays.asList(userLevel));
//user.setAttributes(Collections.singletonMap("origin", Arrays.asList("demo")));
user.setAttributes(attributeMap);
//将创建的用户添加到系统中,创建新用户
Response response = userResource.create(user);
//判断创建用户状态;如果时创建成功
Response.StatusType createUserStatus = response.getStatusInfo();
URI location = response.getLocation();
System.out.println(createUserStatus);
if ("Created".equals(createUserStatus.toString())) {
System.out.println("创建用户成功!");
System.out.println("创建用户的URI:" + location);
} else {
throw new UserManagementException("账号已经存在!");
}
//获取创建用户的userId
String userId = response.getLocation().getPath().replaceAll(".*/([^/]+)$", "$1");
//获取该域下角色为user的描述
String userRoleName = userLevel;
// if (“admin”.equals(userLevel)) {
// userRoleName = “admin”;
// }
//创建角色
RoleRepresentation testerRealmRole = realmResource.roles()
.get(userRoleName).toRepresentation();
userResource.get(userId).roles().realmLevel().add(Arrays.asList(testerRealmRole));
// ClientRepresentation app1Client = realmResource.clients().findByClientId(TARGET_CLIENT_ID).get(0);
// RoleRepresentation userClientRole = realmResource.clients().get(app1Client.getId()) //
// .roles().get(userRoleName).toRepresentation();
// Assign client level role to user
// userResource.get(userId).roles().clientLevel(app1Client.getId()).add(Arrays.asList(userClientRole));
//重置用户密码
CredentialRepresentation passwordCred = new CredentialRepresentation();
passwordCred.setTemporary(false);
passwordCred.setType(CredentialRepresentation.PASSWORD);
passwordCred.setValue(password);
// 重置用户密码
userResource.get(userId).resetPassword(passwordCred);
}
获取用户列表
/**
* 获取用户列表
*
* @return
*/
public JSONArray getUserList() {
Keycloak kcMaster = Keycloak.getInstance(url, MASTER_REALM, adminUserName, adminPassword, clientId);
RealmResource realmResource = kcMaster.realm(TARGET_REALM);
UsersResource userResource = realmResource.users();
List userList = userResource.list();
JSONArray array = new JSONArray();
String userId = UserUtils.getUserId();
for (UserRepresentation user : userList) {
JSONObject object = new JSONObject();
if (userId != null && userId.equals(user.getId())) {
continue;
}
object.put("id", user.getId());
object.put("account", user.getUsername());
object.put("email", user.getEmail());
object.put("userName", user.getFirstName());
Map> userAttributesList = user.getAttributes();
if (userAttributesList != null) {
for (String key : userAttributesList.keySet()) {
object.put(key, userAttributesList.get(key).get(0));
}
array.add(object);
}
}
return array;
}
获取用户信息
public JSONObject getUserInfo(String userId) throws UserManagementException {
Keycloak kcMaster = Keycloak.getInstance(url, MASTER_REALM, adminUserName, adminPassword, clientId);
RealmResource realmResource = kcMaster.realm(TARGET_REALM);
UsersResource userResource = realmResource.users();
if (StringUtils.isEmpty(userId)) {
throw new UserManagementException("userId为空");
}
List userList = userResource.list();
JSONObject object = new JSONObject();
for (UserRepresentation user : userList) {
if (userId.equals(user.getId())) {
object.put("id", user.getId());
object.put("account", user.getUsername());
object.put("email", user.getEmail());
object.put("userName", user.getFirstName());
Map> userAttributesList = user.getAttributes();
for (String key : userAttributesList.keySet()) {
object.put(key, userAttributesList.get(key).get(0));
}
}
}
return object;
}
更新用户信息
public void updateUserInfo(String userId, 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();
if (StringUtils.isEmpty(userId)) {
throw new UserManagementException("userId为空");
}
UserRepresentation user = new UserRepresentation();
user.setEnabled(true);
user.setFirstName(userName);
user.setEmail(email);
Map> attributeMap = new HashMap<>();
attributeMap.put("medicalInsitution", Arrays.asList(medicalInstitution));
attributeMap.put("telephone", Arrays.asList(telephone));
attributeMap.put("code", Arrays.asList(code));
attributeMap.put("userLevel", Arrays.asList(userLevel));
user.setAttributes(attributeMap);
if (!StringUtils.isEmpty(password)) {
CredentialRepresentation passwordCred = new CredentialRepresentation();
passwordCred.setTemporary(false);
passwordCred.setType(CredentialRepresentation.PASSWORD);
passwordCred.setValue(password);
// 重置用户密码
userResource.get(userId).resetPassword(passwordCred);
}
userResource.get(userId).update(user);
}
根据用户id获取用户名
public String getUserNameByUserId(String userId){
if(userId == null){return "";}
JSONObject userInfo = null;
String userName = null;
try {
userInfo = this.getUserInfo(userId);
userName = userInfo.getString("account");
} catch (Exception e) {
e.printStackTrace();
}
return userName;
}
删除用户
public void removeUser(String userId) {
Keycloak kcMaster = Keycloak.getInstance(url, MASTER_REALM, adminUserName, adminPassword, clientId);
RealmResource realmResource = kcMaster.realm(TARGET_REALM);
UsersResource userResource = realmResource.users();
userResource.get(userId).remove();
}
pom依赖
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.0.2.RELEASE
com.neusoft.deepcogni
friend
0.0.1-SNAPSHOT
friend
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-devtools
org.projectlombok
lombok
true
org.keycloak
keycloak-spring-boot-starter
org.jboss.resteasy
resteasy-client
3.0.19.Final
provided
org.jboss.resteasy
resteasy-jaxrs
3.0.19.Final
provided
org.jboss.resteasy
resteasy-jackson2-provider
3.1.0.Final
org.keycloak
keycloak-authz-client
6.0.1
org.keycloak
keycloak-admin-client
6.0.1
javax.ws.rs
javax.ws.rs-api
2.1.1
com.alibaba
fastjson
1.2.17
org.keycloak.bom
keycloak-adapter-bom
5.0.0
pom
import
org.springframework.boot
spring-boot-maven-plugin