JwtSecurityTokenHandler and TokenValidationParameters

后端 未结 1 387
野的像风
野的像风 2021-02-01 17:54

I used to have a reference to Microsoft.IdentityModel.Tokens.JWT and everything was working fine.

I updated to use the new System.IdentityModel.Token

相关标签:
1条回答
  • 2021-02-01 18:19

    After a lot of research and tests, I finally found that some properties names for TokenValidationParameters had changed and JwtSecurityTokenHandler.ValidateToken() method signature too.

    So here's the modified working version of the above code.

    private static void ValidateJwt(string jwt)
    {
        var handler = new JwtSecurityTokenHandler();   
        var validationParameters = new TokenValidationParameters()
        {
            ValidAudience = "https://my-rp.com",
            IssuerSigningTokens = new List<X509SecurityToken>() { new X509SecurityToken(
               X509
               .LocalMachine
               .My
               .Thumbprint
               .Find("UYTUYTVV99999999999YTYYTYTY88888888", false)
               .First()) },
            ValidIssuer = "https://my-issuer.com/trust/issuer",
            CertificateValidator = X509CertificateValidator.None,
            RequireExpirationTime = true
        };
    
        try
        {
            SecurityToken validatedToken;
            var principal = handler.ValidateToken(jwt, validationParameters, out validatedToken);
        }
        catch (Exception e)
        {
    
            Console.WriteLine("{0}\n {1}", e.Message, e.StackTrace);
        }
    
        Console.WriteLine();
    }
    

    And for the reference, the JwtSecurityTokenHandler lives in the System.IdentityModel.Tokens namespace. Don't forget to add the package "JSON Web Token Handler For the Microsoft .Net Framework 4.5" (version 4.0.0 at the time I write theses lines).

    Hope it can save a few hours of search for some of you guys!

    0 讨论(0)
提交回复
热议问题