首页 > 解决方案 > 带有 Microsoft 标识的 JWT RsaSha256

问题描述

我正在使用 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;
            }
        }
    }

任何帮助得到这个工作将不胜感激!

谢谢!

标签: c#google-apijwt

解决方案


推荐阅读