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

.NET 8中如何创建OAuth2 JSON令牌?解决升级后代码失效问题

.NET 7升级到.NET 8后OAuth2令牌生成代码失效问题

将代码从.NET 7升级到.NET 8后,原有生成OAuth2令牌的代码完全失效,常规排查方法无效,导入.NET 7的实现也会抛出异常。我拥有一个PFX格式的RSA证书,需要对固定的客户端ID和新生成的GUID进行签名,生成Bearer断言,再通过HTTPS请求转换为OAuth令牌。现有代码混合了.NET 7的实现逻辑无法正常运行,且相关实用资料多为.NET 7版本,不知如何修改,也不希望从加密原语层面重建OAuth库。

相关代码如下:

var rsaPrivateKey = cert.GetRSAPrivateKey();

var privateSecurityKey = new RsaSecurityKey(rsaPrivateKey);
var now = DateTime.UtcNow;

var handler = new Microsoft.IdentityModel.JsonWebTokens.JsonWebTokenHandler();

#if notdef // Seam
var claims = new[] {
    new Claim(JwtRegisteredClaimNames.Sub, clientId),
    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};

var handler = new JwtSecurityTokenHandler();

var token = new JwtSecurityToken(clientId,
                    GetUrl("oauth2/token"),
                    claims,
                    now.AddMilliseconds(-30),
                    now.AddMinutes(5),
                    new SigningCredentials(privateSecurityKey, SecurityAlgorithms.RsaSha384)
                 );
#endif
// end seam here?

var clientAssert = handler.WriteToken(token);

// or is it here?
var searchParams = new Dictionary<string, string>
        {
            { "grant_type", "client_credentials" },
            { "client_assertion_type" , "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" },
            { "client_assertion" ,  clientAssert }
        };

using var response = await client.PostAsync(GetUrl("oauth2/token"), new FormUrlEncodedContent(searchParams));

其中GetUrl用于获取特定站点的基础地址。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 09:23:25