gpt4 book ai didi

c# - 如何使用 System.IdentityModel.Tokens.Jwt 使用 Google OAuth2 兼容算法 RSA SHA-256 生成 JWT?

转载 作者:太空狗 更新时间:2023-10-29 19:55:49 25 4
gpt4 key购买 nike

我正在尝试创建一个 JWT 以使用服务帐户进行授权,如 Google documentation 中所述使用 System.IdentityModel.Tokens.Jwt .我有以下代码:

byte[] key = Convert.FromBase64String("...");
var certificate = new X509Certificate2(key, "notasecret");

DateTime now = DateTime.UtcNow;
TimeSpan span = now - UnixEpoch;
Claim[] claims =
{
new Claim("iss", "email@developer.gserviceaccount.com"),
new Claim("scope", "https://www.googleapis.com/auth/plus.me"),
new Claim("aud", "https://accounts.google.com/o/oauth2/token"),
new Claim("iat", span.TotalSeconds.ToString()),
new Claim("exp", span.Add(TimeSpan.FromHours(1)).TotalSeconds.ToString())
};

JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
var descriptor = new SecurityTokenDescriptor
{
SigningCredentials = new SigningCredentials(
new InMemorySymmetricSecurityKey(key),
"http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
"http://www.w3.org/2001/04/xmlenc#sha256"),
Subject = new ClaimsIdentity(claims)
};

JwtSecurityToken jwtSecurityToken = (JwtSecurityToken)handler.CreateToken(descriptor);
string json = handler.WriteToken(jwtSecurityToken);

哪些输出:

{ "typ" : "JWT" , "alg" : "HS256" }

虽然 Google 明确声明它支持 SHA-256:

Service accounts rely on the RSA SHA-256 algorithm and the JWT token format

根据 wtSecurityTokenHandler.InboundAlgorithmMap :

RS256 => http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
HS256 => http://www.w3.org/2001/04/xmldsig-more#hmac-sha256

所以当我更改我的代码时:

new SigningCredentials(
new InMemorySymmetricSecurityKey(key),
"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
"http://www.w3.org/2001/04/xmlenc#sha256");

我遇到异常:

System.InvalidOperationException: IDX10632: SymmetricSecurityKey.GetKeyedHashAlgorithm( 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256' ) threw an exception.
SymmetricSecurityKey: 'System.IdentityModel.Tokens.InMemorySymmetricSecurityKey'
SignatureAlgorithm: 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256', check to make sure the SignatureAlgorithm is supported.

这是否意味着 Microsoft 不支持 Google 独家支持的算法?

最佳答案

问这个问题已经有一段时间了,但我认为对于 future 访问此页面的人来说,可能值得知道的是,使用 .NET Google 在几行代码中很容易获得相同的结果Auth API(其 nuget 可在此处获得:Google.Apis.Auth

using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;

namespace GoogleTest
{
public class GoogleOAuth2
{
/// <summary>
/// Authorization scope for our requests
/// </summary>
private readonly string _defaultScope;

/// <summary>
/// Service account will be of the form nnnnnnn@developer.gserviceaccount.com
/// </summary>
private readonly string _serviceAccount;

/// <summary>
/// Set this to the full path to your service account private key file.
/// </summary>
private readonly string _certificateFile;

public GoogleOAuth2(string defaultScope, string serviceAccount, string certificateFile)
{
_defaultScope = defaultScope;
_serviceAccount = serviceAccount;
_certificateFile = certificateFile;
}

/// <summary>
/// Access Token returned by Google Token Server
/// </summary>
public string AccessToken { get; set; }

public async Task<bool> RequestAccessTokenAsync()
{
var certificate = new X509Certificate2(_certificateFile, "notasecret", X509KeyStorageFlags.Exportable);
var serviceAccountCredential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(_serviceAccount)
{
Scopes = new[] { _defaultScope }
}.FromCertificate(certificate));

var status = await serviceAccountCredential.RequestAccessTokenAsync(CancellationToken.None);
if (status)
AccessToken = serviceAccountCredential.Token.AccessToken;
return status;
}
}
}

要获取访问 token ,您只需调用 RequestAccessTokenAsync 方法,如果结果成功,您就会在 AccessToken 属性中获得您的 token 。

请注意,此实现假设您已在开发人员控制台中将私钥导出为 .P12 文件。

希望这个回答对您有所帮助。

关于c# - 如何使用 System.IdentityModel.Tokens.Jwt 使用 Google OAuth2 兼容算法 RSA SHA-256 生成 JWT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26478694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com