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

如何在OpenIddict中创建拥有多个密钥的客户端

在OpenIddict中为客户端配置多个密钥

当然可以,OpenIddict原生支持为单个客户端配置多个密钥,完全能满足同一应用的不同密钥管理需求。

实现方式

如果使用EF Core作为存储提供方,OpenIddict的客户端实体(默认是OpenIddictClient)自带ClientSecrets集合属性,而非单个密钥字段。你只需要向这个集合中添加多个密钥实例即可。

代码示例

创建客户端时,通过OpenIddictClientDescriptor的ClientSecrets集合添加多个密钥:

await manager.CreateAsync(new OpenIddictClientDescriptor
{
    ClientId = "sample-client",
    ClientName = "Sample Application",
    ClientSecrets =
    {
        // 第一个密钥,有效期1年
        new OpenIddictClientSecretDescriptor
        {
            Value = OpenIddictHelpers.HashPassword("first-client-secret"),
            Type = OpenIddictConstants.SecretTypes.SharedSecret,
            ExpirationDate = DateTimeOffset.UtcNow.AddYears(1)
        },
        // 第二个密钥,有效期6个月
        new OpenIddictClientSecretDescriptor
        {
            Value = OpenIddictHelpers.HashPassword("second-client-secret"),
            Type = OpenIddictConstants.SecretTypes.SharedSecret,
            ExpirationDate = DateTimeOffset.UtcNow.AddMonths(6)
        }
    },
    // 按需添加其他客户端配置,比如重定向URI、授权类型等
    RedirectUris = { new Uri("https://yourapp.com/callback") },
    Permissions = { OpenIddictConstants.Permissions.Endpoints.Authorization }
});

注意事项

  • 务必使用OpenIddictHelpers.HashPassword方法对密钥进行哈希后再存储,禁止明文存储密钥。
  • 客户端验证时,OpenIddict会自动遍历该客户端的所有密钥,只要有一个匹配就能通过身份验证。
  • 这种方案可以轻松实现密钥轮换、不同环境(测试/生产)使用不同密钥等场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 00:11:59