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

如何从Keycloak访问令牌中读取用户属性并提取用户信息?

Extracting User Info & Reading Custom Attributes from a Keycloak Access Token

Hey there! Let's break down how to pull user details and access custom attributes from your Keycloak access token step by step. Keycloak uses JWTs for access tokens, so most of this work revolves around decoding that token or using Keycloak's built-in endpoints.

First: Understand the Access Token Structure

Keycloak access tokens are JSON Web Tokens (JWTs) made up of three parts: Header, Payload, and Signature. All the user data you care about lives in the Payload section. You can decode this without verifying the signature for testing, but always validate signatures in production to avoid fake tokens.

1. Decode the JWT (Cross-Language Examples)

Here are quick code snippets for common languages to decode the token and grab basic user info:

Python (using pyjwt)

import jwt

# Replace with your actual access token
access_token = "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6IC..."

# Decode without signature verification (for testing only!)
payload = jwt.decode(access_token, options={"verify_signature": False})

# Pull basic user fields
print(f"Username: {payload.get('preferred_username')}")
print(f"Email: {payload.get('email')}")
print(f"User ID (sub): {payload.get('sub')}")

Java (using jjwt)

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.Claims;
import java.util.Map;

public class KeycloakTokenParser {
    public static void main(String[] args) {
        String accessToken = "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6IC...";
        
        // Decode without signature check (testing only)
        Claims claims = Jwts.parser()
                .setSigningKeyResolver(new io.jsonwebtoken.SigningKeyResolverAdapter() {
                    @Override
                    public byte[] resolveSigningKey(io.jsonwebtoken.JwsHeader header, Claims claims) {
                        return "".getBytes(); // Skip verification for testing
                    }
                })
                .parseClaimsJws(accessToken)
                .getBody();
        
        // Extract basic user info
        String username = claims.get("preferred_username", String.class);
        String email = claims.get("email", String.class);
        String userId = claims.get("sub", String.class);
        
        System.out.println("Username: " + username);
        System.out.println("Email: " + email);
    }
}

Node.js (using jsonwebtoken)

const jwt = require('jsonwebtoken');

const accessToken = "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6IC...";
const payload = jwt.decode(accessToken); // Gets the payload directly

console.log(`Username: ${payload.preferred_username}`);
console.log(`Email: ${payload.email}`);
console.log(`User ID: ${payload.sub}`);

Important Production Note: To validate the signature, fetch your Keycloak realm's public key from http://your-keycloak-domain/auth/realms/your-realm/protocol/openid-connect/certs and use it in your decoding logic instead of skipping verification.

Reading Custom User Attributes

Custom attributes you've set for users in Keycloak won't show up in the token automatically—you need to configure a mapper first. Here's how to do it:

1. Configure Keycloak to Include Attributes in the Token

  1. Log into your Keycloak admin console
  2. Go to your Realm → Clients → Select your client
  3. Switch to the Mappers tab → Click Create
  4. Fill in the details:
    • Mapper Type: Select User Attribute
    • Name: Give it a descriptive name (e.g., department-mapper)
    • User Attribute: Enter the exact name of the custom attribute you created for users (e.g., department)
    • Token Claim Name: Choose what the field will be called in the JWT (can match the attribute name)
    • Check Add to access token → Click Save
  5. Re-generate your access token (old tokens won't have the new attribute!)

2. Extract Custom Attributes from the Token

Custom attributes usually live under the resource_access object in the JWT payload, nested under your client ID. Here's how to grab them:

Python Example

# Using the same payload from earlier
client_id = "your-client-id"
resource_access = payload.get("resource_access", {}).get(client_id, {})
department = resource_access.get("department")

# If you configured the mapper to put the attribute at the top level:
department = payload.get("department")

print(f"User's Department: {department}")

Alternative: Use the Keycloak UserInfo Endpoint

If you don't want to decode the JWT directly, you can call Keycloak's /userinfo endpoint with your access token. This returns a JSON object with all user details (including custom attributes):

curl -X GET "http://your-keycloak-domain/auth/realms/your-realm/protocol/openid-connect/userinfo" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Sample response:

{
  "sub": "a1b2c3d4-5678-90ef-ghij-klmnopqrstuv",
  "preferred_username": "jane_smith",
  "email": "jane@example.com",
  "department": "Marketing"
}

Troubleshooting Common Issues

  • Custom attribute missing from token?: Double-check your mapper configuration—make sure you checked "Add to access token" and re-generated the token.
  • Signature verification fails: Ensure you're using the correct public key for your realm, and that the token hasn't expired.
  • Can't access /userinfo?: Verify your access token has the profile or email scope (depending on what info you're requesting).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:53:52