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

如何反序列化含URL格式字段名的JWT?

解决Actix-Web中提取带URL格式键的JWT自定义Claims问题

核心方案:利用Serde的rename属性映射特殊字段名

由于你的自定义Claims键是包含特殊字符的URL(如https://some-org-url/domain),无法直接作为Rust结构体的字段名,只需通过Serde的#[serde(rename = "完整键名")]属性,将JSON中的特殊键映射到合法的结构体字段即可。

修改后的Claims结构体示例:

#[derive(Debug, Deserialize)]
pub struct Claims {
    iss: String,
    sub: String,
    aud: Vec<String>,
    iat: u32,
    exp: u32,
    azp: String,
    scope: String,
    // 映射自定义URL格式的claims键
    #[serde(rename = "https://some-org-url/domain")]
    pub domain: String,
    #[serde(rename = "https://some-org-url/roles")]
    pub roles: Vec<String>,
    #[serde(rename = "https://some-org-url/tag-list")]
    pub tag_list: Vec<String>,
}

这样在JWT解码验证后,serde会自动将JSON中对应URL键的值填充到结构体的对应字段中,你可以直接在Actix-Web的请求处理逻辑中使用这些自定义Claims数据。

备选方案:用HashMap兜底捕获未知Claims

如果存在未提前定义的自定义Claims,或Claims结构可能动态变化,可以在结构体中添加#[serde(flatten)]标记的HashMap,用来捕获所有未显式声明的字段:

use std::collections::HashMap;
use serde_json::Value;

#[derive(Debug, Deserialize)]
pub struct Claims {
    iss: String,
    sub: String,
    aud: Vec<String>,
    iat: u32,
    exp: u32,
    azp: String,
    scope: String,
    #[serde(rename = "https://some-org-url/domain")]
    pub domain: String,
    #[serde(rename = "https://some-org-url/roles")]
    pub roles: Vec<String>,
    #[serde(rename = "https://some-org-url/tag-list")]
    pub tag_list: Vec<String>,
    // 捕获所有未显式定义的claims
    #[serde(flatten)]
    pub extra_claims: HashMap<String, Value>,
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 00:15:59