JWT验证在.NET Core中有效,在.NET Framework中失败

时间:2019-04-15 09:10:15

标签: c# .net .net-core jwt

类似于here中提到的问题,我遇到一个问题,即在.NET Core 2.2(在macOS和Windows上)上运行时,JWT验证有效,但在.NET Framework 4.7.2上无法运行;在那里,它引发异常:

  

Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException :'IDX10503:签名验证失败。尝试过的密钥:'Microsoft.IdentityModel.Tokens.RsaSecurityKey,KeyId:   '。   捕获的异常:    ”。   令牌:'{“ typ”:“ JWT”,“ alg”:“ RS256”}。{“ sub”:“用户名”,“ scope”:“ examplescope”,“ roles”:[“ examplerole”],“ iss “:” https://example.com/“,” exp“:1556788122,” iat“:1555316893}'。'
     在System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(String token,TokenValidationParametersvalidationParameters)中的C:\ agent1_work \ 109 \ s \ src \ System.IdentityModel.Tokens.Jwt \ JwtSecurityTokenHandler.cs:line 979
     在System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token,TokenValidationParametersvalidationParameters,SecurityToken&validatedToken)中位于C:\ agent1_work \ 109 \ s \ src \ System.IdentityModel.Tokens.Jwt \ JwtSecurityTokenHandler.cs:line 722
     在JWTTest.Program.Main(String [] args)在C:\ Users \ User \ source \ repos \ JWTTest \ JWTTestCore \ Program.cs:line 35

测试程序:

using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;

namespace JWTTest {
    class Program {
        static void Main(string[] args) {
            // Validation parameters
            //var rsa = new RSACryptoServiceProvider(); // this works in .NET Core on macOS but not on Windows ...
            var rsa = RSA.Create();
            rsa.KeySize = 2048;
            rsa.ImportParameters(new RSAParameters {
                  Modulus = Convert.FromBase64String("AM/Nh9cX8U+8ZeOcKyodBcZun1dgQysFZWLplOof9SpHt45vmh7gy3FxhLQEj2NrhV44AiymRxr1mmZ7K9K105MfDe/QAAFBy715/NHmKZxH7QvypiiPMf2jwpb+n/Ss0oUZ68zPSfO9aZwhUBWO+J7NBnWEwoq3Bxda5IQPMRkMohD5VZ0IPvUotcg6k7cOoRamvOiDyVQ58uVx+Wd+vucdVo6uT/kMKlBZoahU/hnREfNZojf0lAkzcxOlZcKbms/+Mu8vb/jeZSGYZpykL0c3ohGJ49NteFIXggx8AH6E8ROpijq2NeA7AK3Y+33LEJmSwOdNnZ1ZaY515AqeN/S+ay4Ra15V91qdu4ph1B+G5aKV3rcu0v1Y6/eG5dgHPIBRaf7sGVG7rCDOgrfbjaEdNvqX1TgNnmfogZElFt2qs5VVWKE5zEuOEkOngTEuvlJAsTgh/Uw/OS7vinbSmtGXFhKS2teatITyuNALaPeFAdA9qz9c90IJs9vbf9Uf9FFWvfrer9lhDhLUuehKJTt8vBtoqea46nf3IGthLeiGQmrVSEytoTGW67gGpVo8Xd+iat5ilhciNWX1/rscv66cg0S1IK7A/oXqWJO/WNq6EzFxI/f/0klMrcC8M5qioiiwNMvpAj/6KDZSxoII+rS9RDz/E0xWprkErrIa7aVv"),
                  Exponent = Convert.FromBase64String("AQAB")
            });
            var validationParameters = new TokenValidationParameters {
                ClockSkew = TimeSpan.FromMinutes(1),
                ValidateAudience = false,
                ValidateIssuer = true,
                ValidIssuer = "https://example.com/",
                IssuerSigningKey = new RsaSecurityKey(rsa)
            };

            // Verify token
            IdentityModelEventSource.ShowPII = true;
            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
            var token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1c2VybmFtZSIsInNjb3BlIjoiZXhhbXBsZXNjb3BlIiwicm9sZXMiOlsiZXhhbXBsZXJvbGUiXSwiaXNzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS8iLCJleHAiOjE1NTY3ODgxMjIsImlhdCI6MTU1NTMxNjg5M30.XHowlwvKX73I2KqKFInaadAGZNtj7UVvjh1EuodnttlUOmC59Q6XPSwrKkATLqicl46c7ItYGl75Mj5PVy03tOXXlxgsgoP81t1WM08QeHlrbPvay1aSFqcj7JcnX6fu9qiXzRhhh2XYw5UrT8-R3kIQMQA7d4cnT6Z1oeoHzV38ywi3rv3BapwuFtrFmSXHHsQMcTUK_Whf-5CEPj6O9CEdCXKFh05McGZDBoYBgZpn7d2H2EJNV9KhsasafsD7TVs6w3myOfc3HaqtHhFDUmpzwmWZdzn-i0zSxz1qussd9ovDaf03zkd7OWtau9_44T1KkWVK8GlAxuXnuPmCuh76ELQjpNqQerRL-F4EYkUwUJEQHFf2IolpCx4i2pDkzyax-fL4ZwjsncWNUJdXyex3Pk-OcSD11lJl0UWRE5gh-pOeEd1Ybhxu4z42Vet1rAM3VWXXyJQzAz2diVTJIbvaG3uq4-HxoBTkvfpXLj_2RN_oSTkyD8JoBIHQtMT1h7eZhHbxFLsxLoGNQVWJmyU_BPCs282m41n2Jd4ezR1M1XlLUixk8v1M1Rjxg3s7c8Q_PezmXzv3IrK8ftrmfb73uBwTxJukOeFk3yC7e7ZLhYJsBlJsyeGfJF8ayNSjxwkrXJN3JVZMOzZCQNnl3zc8AL6gjloFFlhgB5nlxJU";
            // exception is thrown on the next line:
            var user = handler.ValidateToken(token, validationParameters, out SecurityToken validatedToken);

            foreach (var role in user.Claims.Where(c => c.Type == ClaimTypes.Role)) {
                Console.WriteLine("Role: " + role.Value);
            }
        }
    }
}

JWT是用this Java library生成的,但是我不确定这是否重要;根据{{​​3}},它是有效的。 (该链接显示无效签名,但这是网站中的错误;只需在公共密钥的末尾添加换行符即可触发验证。)我已经尝试过由RS256和RS512算法生成的令牌,但这并不能差异。

我不确定是否取决于Visual Studio设置;

  • macOS Mojave 10.14.4; Visual Studio for Mac 7.7.3(内部版本43); .NET Core SDK版本2.2.105(有效)
  • Windows 10版本1809; Visual Studio 2017,v15.9.11
    • .NET Core SDK 2.2.106(有效)
    • .NET Framework 4.7.2 (不起作用)

1 个答案:

答案 0 :(得分:1)

没有Java libray应该不是问题。在您附加的同一链接中提到了该问题。您需要覆盖并使用自定义密钥验证,因为库中的RSA解密附带了某种错误。

请查看thisthis以获得更多信息(同样,该链接与您附上的链接相同)。

该问题被引用到另一个问题中,并且已关闭。除非某些软件包未更新或此处提到的版本,否则应将其修复。