Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyCloak User Federation AND DYNAMIC ROLES

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

like image 892
chege Avatar asked Dec 02 '25 21:12

chege


1 Answers

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);
    }
}
like image 78
Boomer Avatar answered Dec 05 '25 17:12

Boomer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!