KeyCloak用户联合和动态角色 [英] KeyCloak User Federation AND DYNAMIC ROLES
问题描述
我正在使用本指南 http://www. keycloak.org/docs/3.2/server_development/topics/user-storage.html 来配置用户联盟.这样工作正常,我的用户可以登录.
I am using this guide http://www.keycloak.org/docs/3.2/server_development/topics/user-storage.html to configure user federation. This works fine and my users can login.
我的用户存储在Mysql数据库中.用户具有不同的角色-也存储在mysql中.
My users are stored in a Mysql Database. Users have different roles - also store in mysql.
我不确定如何向UserModel添加角色.
I am not not sure of how to add roles to the UserModel.
我已经实现了getUserXXX方法
I've implemented getUserXXX methods
例如
@Override
public UserModel getUserByEmail(String email, RealmModel realm) {
LOGGER.info("LOADING BY EMAIL");
try (Connection connection = ds.getConnection()) {
try (PreparedStatement statement = connection.prepareStatement("select * from user where email = ?")) {
statement.setString(1, email);
try (ResultSet rs = statement.executeQuery()) {
if (rs.next()) {
UserEntity user = new UserEntity();
user.setEmail(rs.getString("email"));
user.setId(rs.getString("email"));
user.setPassword(rs.getString("password"));
return new UserAdapter(session, realm, model, user);
}
}
}
} catch (SQLException ex) {
LOGGER.error(ex.getMessage(), ex);
}
return null;
}
我现在想为每个登录的用户添加特定的角色.我该怎么办?
I now want to add specific roles to each of the users that login. How do I do it?
我的UserAdapter扩展了AbstractUserAdapterFederatedStorage
My UserAdapter extends AbstractUserAdapterFederatedStorage
推荐答案
我已经使用以下方法在几种实现中做到了这一点.在UserModel而不是UserEntity级别上执行此操作.
I've done this in several implementations using a method like the below. Do it on the UserModel and not the UserEntity level.
void updateRoles(UserModel user, List<RoleModel> rolesToRemove, List<RoleModel> rolesToAdd)
{
for (RoleModel role : rolesToRemove)
{
user.deleteRoleMapping(role);
}
for (RoleModel role : rolesToAdd)
{
user.grantRole(role);
}
}
这篇关于KeyCloak用户联合和动态角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!