我在 API Manager-4.2.0 All-in-One 部署中使用自定义后端 JWT 生成器。我需要通过网关生成的后端 JWT 将自定义声明值传递到后端。 虽然当最终用户使用
client-credentials
授权类型登录时它可以工作,但当最终用户使用 authorization_code
授权类型时它会失败。
我的参考文档是:https://apim.docs.wso2.com/en/4.2.0/deploy-and-publish/deploy-on-gateway/api-gateway/passing-enduser-attributes-to-the-后端-via-api-gateway/#jwt-self-contained-access-tokens
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.annotations.Component;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.common.gateway.dto.JWTInfoDto;
import org.wso2.carbon.apimgt.common.gateway.jwtgenerator.APIMgtGatewayJWTGeneratorImpl;
import org.wso2.carbon.apimgt.common.gateway.jwtgenerator.AbstractAPIMgtGatewayJWTGenerator;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import java.util.Map;
import java.util.SortedMap;
@Component(
enabled = true,
service = AbstractAPIMgtGatewayJWTGenerator.class,
name = "CustomGatewayJWTGenerator"
)
/**
* This class will extend the default jwt generator and add Customer ID as an additional claim
*/
public class CustomGatewayJWTGenerator extends APIMgtGatewayJWTGeneratorImpl {
private static final Log LOG = LogFactory.getLog(CustomGatewayJWTGenerator.class);
@Override
public Map<String, Object> populateCustomClaims(JWTInfoDto jwtInfoDto) {
Map<String, Object> claims = super.populateCustomClaims(jwtInfoDto);
SortedMap<String, String> userClaims;
String customerIdClaimURI;
try {
customerIdClaimURI = "http://wso2.org/claims/customerId";
userClaims = APIUtil.getClaims(jwtInfoDto.getEndUser(), jwtInfoDto.getEndUserTenantId(),
getDialectURI());
if (userClaims.containsKey(customerIdClaimURI)) {
claims.put(customerIdClaimURI, userClaims.get(customerIdClaimURI));
}
} catch (APIManagementException e) {
LOG.error("Error occurred when populating custom claims", e);
}
return claims;
}
}
在调试时,观察到
APIUtil.getClaims()
失败,因为 jwtInfoDto.getEndUser()
返回 userId
而不是 userName
并抛出错误,提示 User does not exist in the UserStore
。
感谢任何解决问题的帮助。