我该如何在.net 8 中创建 json oath2 令牌?

问题描述 投票:0回答:1

此代码因从 .net 7 升级到 .net 8 而被破坏,我正在尝试恢复它。

这相当残酷;寻找这些东西的正常方法不起作用;看来可以继续导入 .net 7 实现,但该程序集会抛出异常。

我在 PFX 文件中有一个 RSA 证书,我需要签署我的客户端 ID(这是一个不会更改的长字符串)和一个新的 guid,从而生成一个不记名断言,该断言通过 https 调用转换为 oauth 令牌.

我们这里的内容是从 .NET 代码开始,然后突然切换到 .NET 7 并且不起作用。所有有用的文章仍然适用于 .NET 7。Oof.

            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 只是获取特定于站点的安装基础。

我不知道从这里该去哪里。从加密原语重建 oauth 库不太可能是明智之举。

c# .net oauth-2.0 jwt bearer-token
1个回答
0
投票

也许您可以尝试使用 PFX 文件中的 RSA 私钥创建 JWT 令牌,并使用 RSA-SHA384 算法对该令牌进行签名。然后,JWT 用作

OAuth2
令牌请求中的承载断言。请记住将“path_to_certificate.pfx”、“password”、“your_client_id”和“your_audience”等占位符替换为您的实际值。 GetUrl 函数应返回您的
OAuth2
令牌端点的适当 URL。

请参阅我的示例,我更新了您的代码片段,它应该可以在 .NET 8 中工作。假设您在 PFX 文件中有一个证书并且需要用它来签署您的 JWT,请尝试以下操作:

using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using Microsoft.IdentityModel.Tokens;

// Load your certificate (assuming it's loaded from a file)
var cert = new X509Certificates.X509Certificate2("path_to_certificate.pfx", "password");

var rsaPrivateKey = cert.GetRSAPrivateKey();

var privateSecurityKey = new RsaSecurityKey(rsaPrivateKey);

var now = DateTime.UtcNow;

var handler = new JwtSecurityTokenHandler();

var clientId = "your_client_id"; // Replace with your actual client ID
var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(new[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, clientId),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
    }),
    Issuer = clientId,
    Audience = "your_audience", // Replace with your actual audience
    IssuedAt = now,
    NotBefore = now,
    Expires = now.AddMinutes(5),
    SigningCredentials = new SigningCredentials(privateSecurityKey, SecurityAlgorithms.RsaSha384)
};

var token = handler.CreateToken(tokenDescriptor);
var clientAssert = handler.WriteToken(token);

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 client = new HttpClient();
using var response = await client.PostAsync(GetUrl("oauth2/token"), new FormUrlEncodedContent(searchParams));
// Process the response as needed
© www.soinside.com 2019 - 2024. All rights reserved.