Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update User Role Mapping in Keycloak using User Storage SPI

Tags:

roles

keycloak

I have developed a Keycloak Provider and have registered it under User Federation. My users are stored in a MySQL Database. It is working fine, and whenever getUserById() is called, keycloak calls my implemented method, and user with proper roles are returned, and the user gets cached. The problem occurs when I update user roles externally (in some other/external portal), now I want to tell Keycloak to invalidate the cache (may be via some REST API), so that it calls my getUserById() or getUserByUsername() method again.

What is the best possible way to do it?

Thanks!

like image 444
Faiza Aslam Avatar asked Nov 15 '25 20:11

Faiza Aslam


1 Answers

Dealing with cache sometimes is undersirable for Authentication purposes, you can force your User Storage to load user from database every time isValid method is called.

In Example:

I put this code at top of isValid method.

public boolean isValid(RealmModel realm, UserModel user, CredentialInput input)
{
        CustomUserAdapter userDb;
        if (user instanceof CachedUserModel)
        {
            userDb = (CustomUserAdapter)this.getUserByUsername(user.getUsername(), realm);
        }
        else if (user instanceof CustomUserAdapter)
        {
            userDb = (CustomUserAdapter)user;
        }
[...]
Your custom code
[...]
}

Another way is change your User Federation Settings by setting Cache Policy to NO_CACHE.

Disable Cache Policy User Storage SPI

like image 151
jose-león-primestone Avatar answered Nov 17 '25 11:11

jose-león-primestone