问题
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.
My users are stored in a Mysql Database. Users have different roles - also store in mysql.
I am not not sure of how to add roles to the UserModel.
I've implemented getUserXXX methods
e.g
@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?
My UserAdapter extends AbstractUserAdapterFederatedStorage
回答1:
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);
}
}
来源:https://stackoverflow.com/questions/46740867/keycloak-user-federation-and-dynamic-roles