KeyCloak User Federation AND DYNAMIC ROLES

自闭症网瘾萝莉.ら 提交于 2021-02-10 07:08:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!