You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于WildFly的Keycloak Java Adapter获取用户角色列表问题

Absolutely, the Keycloak Java Adapter is not limited to just authentication—once a user is successfully authenticated, you can easily pull their assigned roles, client metadata, and realm details through the adapter’s built-in API. Let’s break this down with practical examples tailored to your WildFly setup:

1. Access the Keycloak Security Context

After authentication, the Keycloak-specific security context is attached to the user’s session. You can retrieve it using Java EE’s SecurityContext or Keycloak’s helper methods.

Example in a Servlet

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.keycloak.KeycloakSecurityContext;
import org.keycloak.representations.AccessToken;

@WebServlet("/user-roles")
public class UserRolesServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // Fetch the KeycloakSecurityContext from the request session
        KeycloakSecurityContext securityContext = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
        
        if (securityContext != null) {
            AccessToken accessToken = securityContext.getToken();
            
            // Get realm-level roles assigned to the user
            response.getWriter().println("Realm Roles: " + accessToken.getRealmAccess().getRoles());
            
            // Get client-specific roles (replace "your-client-id" with your actual client ID)
            response.getWriter().println("\nClient Roles (your-client-id): " + accessToken.getResourceAccess("your-client-id").getRoles());
            
            // You can also pull other user/realm details from the token
            response.getWriter().println("\nUsername: " + accessToken.getPreferredUsername());
            response.getWriter().println("Realm Name: " + accessToken.getIssuer().split("/")[3]);
        } else {
            response.getWriter().println("User is not authenticated.");
        }
    }
}

Example with CDI (Jakarta EE)

If you’re using CDI, you can inject the KeycloakSecurityContext directly for cleaner code:

import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import org.keycloak.KeycloakSecurityContext;
import org.keycloak.representations.AccessToken;

@Path("/user-info")
public class UserInfoResource {

    @Inject
    private KeycloakSecurityContext securityContext;

    @GET
    @Path("/roles")
    public String getUserRoles() {
        AccessToken token = securityContext.getToken();
        
        StringBuilder roleDetails = new StringBuilder();
        roleDetails.append("Realm Roles: ").append(token.getRealmAccess().getRoles()).append("\n");
        roleDetails.append("Client Roles: ").append(token.getResourceAccess("your-client-id").getRoles()).append("\n");
        
        return roleDetails.toString();
    }
}

2. Key Details to Keep in Mind

  • Realm vs. Client Roles: getRealmAccess().getRoles() returns roles assigned at the realm level, while getResourceAccess("client-id").getRoles() pulls roles specific to that client.
  • Configuration Check: Ensure your keycloak.json (in WEB-INF/ of your WAR) is properly set up with your realm name, client ID, and authentication endpoints—this is required for the adapter to populate the security context correctly.
  • WildFly Subsystem: Confirm the Keycloak subsystem is enabled in your WildFly standalone.xml/domain.xml, and your deployment has the correct security constraints (e.g., via web.xml or annotations like @RolesAllowed).

3. Is the Adapter Only for Authentication?

Nope! The adapter handles the full authentication lifecycle and gives you access to the parsed JWT token and its metadata. Since the token already contains all role information, using the adapter is far more efficient than calling Keycloak’s REST API directly—it leverages the existing authenticated session and avoids extra network calls.

内容的提问来源于stack exchange,提问作者Anonimo142

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 06:43:08