Verifying JWT signed with the RS256 algorithm using public key in C#

后端 未结 6 599
遥遥无期
遥遥无期 2020-11-27 12:26

Ok, I understand that the question I am asking may be pretty obvious, but unfortunately I lack the knowledge on this subject and this task seems to be quite tricky for me.

6条回答
  •  忘掉有多难
    2020-11-27 12:58

    NET Core

    To use this in a .NET core web api (.NET Framework see below) in a AddJwtBearer() auth flow I enhanced NvMat's great answer:

    Very important is to not use the RSACryptoServiceProvider in an using statement.

        private TokenValidationParameters GetTokenValidationParameters(string key)
        {
            var rs256Token = key.Value.Replace("-----BEGIN PUBLIC KEY-----", "");
            rs256Token = rs256Token.Replace("-----END PUBLIC KEY-----", "");
            rs256Token = rs256Token.Replace("\n", "");
    
            var keyBytes = Convert.FromBase64String(rs256Token);
    
            var asymmetricKeyParameter = PublicKeyFactory.CreateKey(keyBytes);
            var rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;
            var rsaParameters = new RSAParameters
            {
                Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned(),
                Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned()
            };
            var rsa = new RSACryptoServiceProvider();
    
            rsa.ImportParameters(rsaParameters);
    
            var validationParameters = new TokenValidationParameters()
            {
                RequireExpirationTime = false,
                RequireSignedTokens = true,
                ValidateAudience = false,
                ValidateIssuer = false,
                IssuerSigningKey = new RsaSecurityKey(rsa),
            };
    
            return validationParameters;
        }
    

    Then you are able to use authentication in the startup like this:

    services.AddAuthentication(x =>
    {
        x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.RequireHttpsMetadata = false;
        options.SaveToken = true;
        options.IncludeErrorDetails = true;
        options.TokenValidationParameters = GetTokenValidationParameters(configuration["Key"]);
        options.Audience = configuration["ClientId"];
    });
    

    NET Framework

    It is also possible to use this approach in a .NET Framework web api project. All you have to do is add this line to your startup Configure() method:

    app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions()
    {
         TokenValidationParameters = GetTokenValidationParameters(ConfigurationManager.AppSettings["Key"])
    });
    

    One important thing: Make sure you use a verion >=5.0.0 of the JwtSecurityTokenHandler I had problems with the 4.X.X versions.

提交回复
热议问题