在C#中手动验证JWT令牌 [英] Manually validating a JWT token in C#

查看:564
本文介绍了在C#中手动验证JWT令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

手动验证 Identity Server 4发行的JWT令牌时遇到麻烦.使用

I am having some trouble manually validating a JWT token issued by Identity Server 4. Using the

ClientId:"CLIENT1" ClientSecret:"123456"

ClientId: "CLIENT1" ClientSecret: "123456"

我一直收到的异常是:IDX10501:签名验证失败.无法匹配键:'[PII默认情况下是隐藏的.将IdentityModelEventSource.cs中的'ShowPII'标志设置为true以显示它.]'

The exception I keep getting is: IDX10501: Signature validation failed. Unable to match keys: '[PII is hidden by default. Set the 'ShowPII' flag in IdentityModelEventSource.cs to true to reveal it.]'

有人能告诉我我要去哪里了吗

Is anyone able to advise me where I am going wrong.

    private static void ValidateJwt(string jwt, DiscoveryResponse disco)
    {        

        var parameters = new TokenValidationParameters
        {

            ValidateIssuerSigningKey = true,
            ValidIssuer = disco.Issuer,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("123456")),               
            ValidAudience = "CLIENT1",
            //IssuerSigningKeys = keys,
            // ValidateAudience = true,
            // ValidateLifetime = true,
        };

        SecurityToken validatedToken;
        var handler = new JwtSecurityTokenHandler();
        handler.InboundClaimTypeMap.Clear();

        try
        {
            var user = handler.ValidateToken(jwt, parameters, out validatedToken);
        }
        catch(Exception ex)
        {
            var error = ex.Message;
        }

    }

推荐答案

在此示例中查看ValidateJwt():

https://github .com/IdentityServer/IdentityServer4/blob/master/samples/Clients/old/MvcManual/Controllers/HomeController.cs

您缺少的一点是从发现文档中加载公钥.

The bit you're missing is loading the public key from the discovery document.

这篇关于在C#中手动验证JWT令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆