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

WSO2 APIM网关JWT生成器无法传递用户档案信息求助

WSO2 APIM 传递用户档案信息到后端解决方案

问题根源

当API调用直接使用JWT令牌而非Opaque Token时,[apim.jwt]下配置的generator_impl(即你的CustomTokenGenerator)不会被触发——此时网关会直接使用本地的gateway_generator处理JWT,跳过APIM的远程验证流程。


方案一:通过自定义网关JWT生成器获取用户档案

直接修改自定义GatewayJWTGenerator,从用户存储中提取档案信息,步骤如下:

1. 编写自定义网关JWT生成器

继承GatewayJWTGenerator,重写populateCustomClaims方法,调用用户存储服务获取用户属性:

public class CustomGatewayJWTGenerator extends GatewayJWTGenerator {

    @Override
    public Map<String, String> populateCustomClaims(JWTInfoDto jwtInfoDto, MessageContext messageContext) throws APIManagementException {
        Map<String, String> customClaims = new HashMap<>();
        
        // 获取租户感知用户名
        String tenantAwareUsername = jwtInfoDto.getEndUserName();
        
        // 调用IdentityMgtService获取用户档案
        try {
            IdentityMgtService identityMgtService = ServiceReferenceHolder.getInstance().getIdentityMgtService();
            User user = identityMgtService.getUser(new User(tenantAwareUsername));
            
            // 添加需要传递的用户属性
            customClaims.put("email", user.getEmail());
            customClaims.put("phoneNumber", user.getPhoneNumber());
            customClaims.put("fullName", user.getFullName());
            // 其他自定义属性...
            
        } catch (UserStoreException e) {
            throw new APIManagementException("Failed to fetch user profile data", e);
        }
        
        return customClaims;
    }
}

2. 调整deployment.toml配置

保留网关生成器配置,移除无用的generator_impl配置:

[apim.jwt]
enable = true
enable_user_claims = true

[apim.jwt.gateway_generator]
impl = "org.wso2.carbon.test.CustomGatewayJWTGenerator"

方案二:强制使用JWTGenerator(远程验证模式)

若需统一在APIM侧处理用户Claims,可将API设置为远程验证模式,触发CustomTokenGenerator:

1. 修改API验证方式

在API发布/编辑页面,将Token Validation Method设置为Remote Validation或Remote JWKS,使网关将JWT发送至APIM进行验证。

2. 调整deployment.toml配置

启用远程JWT生成器,注释网关生成器:

[apim.jwt]
enable = true
generator_impl = "org.wso2.carbon.test.CustomTokenGenerator"
enable_user_claims = true
claims_extractor_impl = "org.wso2.carbon.test.CustomClaimRetriever" # 对应你的自定义ClaimRetriever

# 注释网关生成器,优先使用远程生成逻辑
# [apim.jwt.gateway_generator]
# impl = "org.wso2.carbon.test.CustomGatewayJWTGenerator"

注意事项

  • 该模式会增加网关与APIM的网络调用,可能影响性能,需根据实际场景评估。

通用排查步骤

  1. 将自定义类打包为JAR,放入APIM和网关的<APIM_HOME>/repository/components/lib目录,重启服务。
  2. 开启调试日志:在log4j2.properties中添加logger.jwt.name = org.wso2.carbon.apimgt.gateway.handlers.security.jwt并设置级别为DEBUG,验证生成器是否被调用。
  3. 使用jwt.io解析后端收到的JWT,确认用户档案Claims是否存在。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 13:35:33