Keycloak - Client Roles - Retrieve custom attributes

3 min read 06-10-2024
Keycloak - Client Roles - Retrieve custom attributes


Accessing User Data with Custom Attributes in Keycloak: A Practical Guide

Keycloak, the popular open-source identity and access management solution, offers robust capabilities for managing user roles and permissions. One of its key features is the ability to define custom attributes, enriching user profiles with specific information beyond basic details like name and email. But how can you effectively retrieve and use these custom attributes for your applications? This article will guide you through the process of leveraging custom attributes in your Keycloak client applications.

The Scenario: Need for Custom Information

Imagine you are building a web application that manages employee profiles. You need to store additional information specific to your company, like employee ID, department, or job title. Keycloak allows you to define these attributes as "custom attributes," extending user profiles with contextually relevant information.

Setting up Custom Attributes in Keycloak

  1. Create the custom attribute:

    • Log into your Keycloak administration console.
    • Navigate to the "Clients" section and select your application.
    • Choose "Realm" > "Users" > "Attributes" and click "Add Attribute."
    • Provide a name for your custom attribute, such as "employeeId" or "department."
    • Choose a data type (String, Boolean, etc.).
    • Save the new attribute.
  2. Assign values to the attribute:

    • Go to "Users" and select the specific user for whom you want to set the custom attribute.
    • Find the custom attribute you created in the "Attributes" section.
    • Enter the relevant value and save the changes.

Retrieving Custom Attributes in Your Client Application

Now that you have custom attributes defined and populated, you can retrieve them in your client application using the Keycloak API.

Keycloak Admin Client:

The Keycloak Admin Client (KAC) provides a powerful way to interact with Keycloak. You can use it to fetch user details, including custom attributes, programmatically:

import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.KeycloakBuilder;
import org.keycloak.admin.client.resource.UsersResource;
import org.keycloak.representations.idm.UserRepresentation;

public class RetrieveCustomAttributes {

    public static void main(String[] args) {

        Keycloak keycloak = KeycloakBuilder.builder()
                .serverUrl("http://localhost:8080/auth")
                .realm("your-realm")
                .clientId("your-client-id")
                .clientSecret("your-client-secret")
                .build();

        UsersResource usersResource = keycloak.realm("your-realm").users();
        UserRepresentation user = usersResource.get("user-id"); // Get the user by their ID

        // Retrieve the value of a custom attribute "employeeId"
        String employeeId = user.getAttribute("employeeId").get(0);
        
        System.out.println("Employee ID: " + employeeId);

        keycloak.close();
    }
}

Keycloak OpenID Connect (OIDC) Protocol:

You can also retrieve custom attributes via the OIDC protocol, which is commonly used for authentication and authorization.

  1. Configure your client to request the attribute:

    • Go to your client configuration in Keycloak and enable "Full Profile" in the client scopes.
    • Additionally, you can specify the specific attributes to be retrieved.
  2. Access attributes from the ID token:

    • When a user successfully authenticates, an ID token containing user information will be returned.
    • You can decode and parse the ID token to access the "custom attributes" section, containing your custom attribute values.

Code example (using JWT library in Java):

import com.nimbusds.jwt.JWTParser;
import com.nimbusds.jwt.JWTClaimsSet;

public class RetrieveCustomAttributesFromToken {

    public static void main(String[] args) throws Exception {

        String idToken = "your-id-token"; // Get the ID token from the authentication response

        JWTClaimsSet claimsSet = JWTParser.parse(idToken).getJWTClaimsSet();

        // Retrieve the custom attribute "department" from the ID token
        String department = claimsSet.getStringClaim("department");

        System.out.println("Department: " + department);
    }
}

Conclusion

Keycloak's custom attributes offer a valuable mechanism for storing additional user information, enriching your application's functionality. Understanding how to retrieve these attributes via the Admin Client or OIDC protocol allows you to seamlessly access and use this crucial user data in your applications. By leveraging custom attributes, you can enhance user profiles, personalize experiences, and streamline your application's functionality based on specific user information.