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

如何在启用JWT认证的Ballerina服务资源函数中读取JWT负载

在Ballerina中读取JWT负载的最佳实践

如果你已经有一个用JWT认证保护的Ballerina服务,读取JWT负载最直接高效的方式是利用Ballerina内置auth模块提供的上下文属性,无需手动解析token字符串。

核心实现步骤

  • 确保你的服务已通过auth:JwtValidator配置好JWT认证(这是前提,你应该已经完成该配置)
  • 在资源函数中,通过服务上下文(ctx)的auth字段获取已解析的auth:JwtPayload对象
  • 直接访问JwtPayload的内置标准声明(如sub、iss、exp),或通过方法获取自定义声明

完整示例代码

import ballerina/http;
import ballerina/auth;

// 配置JWT验证器参数
configurable string jwtIssuer = "https://your-issuer.com";
configurable string jwtAudience = "your-service-audience";
configurable string jwtPublicKey = "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----";

service /api on new http:Listener(9090) {
    // 绑定JWT认证拦截器,验证请求中的JWT
    @http:Interceptor {
        interceptor: auth:JwtValidator {
            issuer: jwtIssuer,
            audience: jwtAudience,
            signatureConfig: {publicKey: jwtPublicKey}
        }
    }
    resource function get userInfo(http:Request req, http:Caller caller, http:Context ctx) returns error? {
        // 从上下文获取已验证解析的JWT负载
        auth:JwtPayload payload = ctx.auth as auth:JwtPayload;

        // 访问JWT标准声明
        string userId = payload.sub;
        string tokenIssuer = payload.iss;
        int expiryTimestamp = payload.exp;

        // 访问自定义声明(示例:获取用户角色)
        string userRole = payload.getClaimValue("role");

        // 基于负载数据返回响应
        json userResponse = {
            userId: userId,
            role: userRole,
            expiresAt: expiryTimestamp
        };

        check caller->respond(userResponse);
    }
}

关键说明

  • ctx.auth会自动包含经过验证的JWT负载,类型为auth:JwtPayload,无需手动解析请求头中的token字符串
  • 标准JWT声明已作为JwtPayload的内置属性存在,直接调用即可
  • 自定义声明可通过getClaimValue(string claimName)方法获取,返回值为anydata,可根据实际业务场景做类型转换
  • 只有通过JWT验证的请求才会进入资源函数,因此无需额外校验负载的有效性

内容的提问来源于stack exchange,提问作者Kavindu Gimhan Zoysa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 20:55:09