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

如何在Axum中使用jwt-authorizer Rust crate提取client_id自定义声明

解决Axum中jwt-authorizer提取自定义client_id声明的问题

问题分析

你当前的自定义Claims结构体缺少jwt-authorizer所需的解析特征实现,导致无法正确从JWT中反序列化出client_id字段;若需要同时访问标准注册声明(如exp、iss),还需将RegisteredClaims与自定义声明结合处理。

修正步骤

1. 为自定义Claims添加必要的Derive宏

修改你的Claims结构体,添加jwt_authorizer::DecodeableClaims的derive宏,同时如果需要访问标准注册声明,通过#[serde(flatten)]嵌入RegisteredClaims字段:

use jwt_authorizer::{DecodeableClaims, RegisteredClaims};
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize, Clone, Debug, DecodeableClaims)]
pub struct Claims {
    pub client_id: String,
    // 可选:嵌入标准注册声明,方便直接访问exp/iss等字段
    #[serde(flatten)]
    pub registered: RegisteredClaims,
}

2. 确认JWT payload包含client_id字段

确保你的JWT载荷中确实存在client_id自定义声明,格式示例:

{
  "client_id": "your-client-identifier",
  "exp": 1718923200,
  "iss": "https://your-sso-realm-url"
}

3. 路由中正常提取自定义声明

你的路由函数写法本身无问题,修正Claims结构体后,即可直接通过user_token.client_id获取自定义声明:

#[debug_handler]
pub async fn find_saldo(
    Path(conta_string): Path<String>,
    query_params: Query<QueryParams>,
    header_map: HeaderMap,
    JwtClaims(user_token): JwtClaims<Claims>,
    State(client): State<Client>,
) -> Result<Json<SaldoDTO>, Error> {
    // 正常获取自定义client_id声明
    println!("#### USER FROM TOKEN {:?}", user_token.client_id);
    // 若嵌入了RegisteredClaims,也可直接访问标准字段
    println!("#### Token expires at {:?}", user_token.registered.exp);
    
    // 后续业务逻辑...
}

关键说明

  • DecodeableClaims是jwt-authorizer提供的核心特征,用于告知库如何解析自定义JWT声明,必须为自定义Claims结构体derive该特征才能完成反序列化。
  • #[serde(flatten)]用于将标准注册声明的字段平合并入自定义Claims结构体,避免嵌套访问,若不需要标准声明可直接省略该字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 05:11:10