C# 具有Microsoft标识的JWT RSASA256

C# 具有Microsoft标识的JWT RSASA256,c#,google-api,jwt,C#,Google Api,Jwt,我正在使用Google API创建一个服务到服务的应用程序,我在身份验证方面遇到了问题 也许是因为我对RS256协议缺乏了解,因为我已经看完了这里的问题,不明白我做错了什么。下面的代码过去使用过HmacSha256,但当我尝试对RSA执行相同操作时,会出现异常错误 using System.IdentityModel.Tokens.Jwt; using Microsoft.IdentityModel.Tokens; public

我正在使用Google API创建一个服务到服务的应用程序,我在身份验证方面遇到了问题

也许是因为我对RS256协议缺乏了解,因为我已经看完了这里的问题,不明白我做错了什么。下面的代码过去使用过HmacSha256,但当我尝试对RSA执行相同操作时,会出现异常错误

        using System.IdentityModel.Tokens.Jwt;
        using Microsoft.IdentityModel.Tokens;    
    
        public static string Generate(string user, string privatekey)
        {
            {
                DateTime Expiry = DateTime.Today.AddMinutes(45);
                int expiryTimeStamp = (int)(Expiry - new DateTime(1970, 1, 1)).TotalSeconds;
                int iat = (int)(DateTime.Now - new DateTime(1970, 1, 1)).TotalSeconds;

                var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(privatekey));
                var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256Signature);
                var header = new JwtHeader(credentials);
                var payload = new JwtPayload
                {
                    { "iss", user }, //Service user unique email
                    { "scope", "https://www.googleapis.com/auth/admin.reports.usage.readonly" }, //Scope of data
                    { "aud", "https://oauth2.googleapis.com/token" },
                    { "exp", expiryTimeStamp },
                    { "iat", iat },
                };

                var secToken = new JwtSecurityToken(header, payload);
                var handler = new JwtSecurityTokenHandler();
                var tokenString = handler.WriteToken(secToken);

                return tokenString;
            }
        }
    }
任何帮助这项工作将非常感谢


谢谢

这回答了你的问题吗?因此,无论您遇到什么错误(下次在文章中包含它们),最明显的错误是:
var securityKey=new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(privatekey)),因为专用RSA密钥不是SymmetricKey。请参阅链接副本,了解如何加载RSA密钥并使用它对令牌进行签名。感谢您的回复!你是对的,提交密钥是关键。但我仍然很困惑这个特殊的密钥对是如何工作的。我已经下载了私钥,作为解析的JSON文件的一部分。公钥托管在另一个URL上,我需要下载该密钥并将其放在本地吗?您可以显示JSON(至少是结构,您可以“xxx”值。公钥仅用于验证。听起来像JWK(JSON Web密钥)。请参见此处: