首页
/ JWT.NET 项目中如何利用 JWKS 验证 JWT 令牌

JWT.NET 项目中如何利用 JWKS 验证 JWT 令牌

2025-07-03 16:04:31作者:胡唯隽

在 JWT.NET 项目中,开发者经常需要处理来自不同身份提供者的 JWT 令牌验证。本文将详细介绍如何利用 JWKS(JSON Web Key Set)来验证 JWT 令牌的签名,特别是当身份提供者使用多组密钥并动态轮换时。

JWKS 简介

JWKS 是 JSON Web Key Set 的缩写,它是一种标准化的格式,用于表示一组加密密钥。在 OAuth 2.0 和 OpenID Connect 协议中,身份提供者通常会提供一个 JWKS 端点,客户端可以通过该端点获取当前有效的公钥集合。

典型的 JWKS 响应格式如下:

{
    "keys": [
        {
            "kty": "RSA",
            "kid": "唯一密钥标识符",
            "use": "sig",
            "n": "模数",
            "e": "指数"
        }
    ]
}

实现方案

1. 定义数据模型

首先需要定义对应的 C# 模型来表示 JWKS 数据结构:

internal sealed class JsonWebKey
{
    [JsonPropertyName("kid")]
    public string KeyId { get; set; } = null!;

    [JsonPropertyName("n")]
    public string Modulus { get; set; } = null!;

    [JsonPropertyName("e")]
    public string Exponent { get; set; } = null!;
}

internal sealed class JsonWebKeySet
{
    public IEnumerable<JsonWebKey> Keys { get; set; } = null!;
}

[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(JsonWebKeySet))]
internal partial class JsonWebKeySetContext : JsonSerializerContext;

2. 实现算法工厂

JWT.NET 提供了 IAlgorithmFactory 接口,我们可以实现它来根据 JWT 头部中的 kid 选择对应的密钥:

internal sealed class AlgorithmFactory : IAlgorithmFactory
{
    private readonly Dictionary<string, JsonWebKey> keys;

    public AlgorithmFactory(JsonWebKeySet keySet) 
    {
        keys = keySet.Keys.ToDictionary(x => x.KeyId);
    }

    public IJwtAlgorithm Create(JwtDecoderContext context)
    {
        if (!keys.TryGetValue(context.Header.KeyId, out var key))
            throw new SignatureVerificationException("无效或缺失的密钥");

        var rsaParameters = new RSAParameters
        {
            Modulus = WebEncoders.Base64UrlDecode(key.Modulus),
            Exponent = WebEncoders.Base64UrlDecode(key.Exponent)
        };

        return new RS256Algorithm(RSA.Create(rsaParameters));
    }
}

3. 配置 JWT 解码器

最后,我们需要配置 JWT 解码器使用我们的自定义算法工厂:

var serializer = new SystemTextSerializer();
var validator = new JwtValidator(serializer, new UtcDateTimeProvider());

// 从身份提供者获取 JWKS
var keySet = JsonSerializer.Deserialize(jwksResponse, JsonWebKeySetContext.Default.JsonWebKeySet)!;

// 创建解码器
var algorithmFactory = new DelegateAlgorithmFactory(new AlgorithmFactory(keySet));
var decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithmFactory);

// 解码令牌
var payload = decoder.Decode(token);

工作原理

  1. 当解码器处理 JWT 令牌时,会先解析头部获取 kid
  2. 通过 IAlgorithmFactory 接口的 Create 方法,根据 kid 查找对应的公钥
  3. 将 JWK 中的模数(n)和指数(e)转换为 RSA 参数
  4. 创建 RS256 算法实例用于验证签名
  5. 如果找不到对应的密钥,抛出 SignatureVerificationException 异常

最佳实践

  1. 缓存 JWKS:身份提供者的 JWKS 端点通常不会频繁变更,应该缓存响应结果
  2. 错误处理:实现适当的错误处理机制,特别是网络请求失败的情况
  3. 密钥轮换:考虑定期刷新 JWKS 以支持密钥轮换策略
  4. 性能优化:对于高并发场景,可以考虑预先生成所有 RSA 实例

通过这种方式,我们可以灵活地处理来自不同身份提供者的 JWT 令牌,同时支持密钥的动态更新和轮换,提高了系统的安全性和可维护性。

登录后查看全文
热门项目推荐
相关项目推荐