使用 Jwt-Dotnet 生成有效令牌

时间:2023-03-29
本文介绍了使用 Jwt-Dotnet 生成有效令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在使用以下代码,最初是从

通过查看您的代码,您的代码中包含的值是:

ConfigurationManager.AppSettings["jwt-key"];

只需在秘密"文本框中输入值,如果令牌的签名与 JWT.io 计算的签名匹配,那么您将收到一条消息,说明签名有效.

I am using the following code, which I borrowed originally from the jwt-dotnet github page

    private static string CreateToken(UserPrincipal principal)
    {
        /*
         * https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
         * http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html
         */
        var key = ConfigurationManager.AppSettings["jwt-key"];

        var claims = new Dictionary<string, string>()
        {
            {ClaimTypes.Name, "Rainbow Dash" },
            {ClaimTypes.WindowsAccountName, "RDash"}
        };

        var algorithm = new HMACSHA256Algorithm();
        var serializer = new JsonNetSerializer();
        var urlEncoder = new JwtBase64UrlEncoder();
        var encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
        var token = encoder.Encode(claims, key);
        return token;
    }

The above code generates the following token:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiUmFpbmJvdyBEYXNoIiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2NsYWltcy93aW5kb3dzYWNjb3VudG5hbWUiOiJSRGFzaCJ9.5WZWDJ0pvTe6QLjVNUeTfZicX_wSsk1dtYvXUbpiOiw

So, I hopped over to jwt.io to test my token. I'm told I have an invalid signature.

How do I give it a valid 'signature'? I don't understand what my JWT is missing.

解决方案

The tool over JWT.io can verify the digital signature of your token if you give it the secret signing key you used while creating a token:

And from looking at your code it's the value contained in your:

ConfigurationManager.AppSettings["jwt-key"];

Just input the value inside the "secret" text box and if the signature of the token matches the one calculated by JWT.io then you'll get a message saying that the signature is valid.

这篇关于使用 Jwt-Dotnet 生成有效令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:Asp Core 2.1 Jwt + 身份.userManager 存储没有实现 IUserRoleStore 下一篇:如何验证 JWT 令牌

相关文章