using Jwt-Dotnet to generate a valid token

2020-01-30 01:37发布

问题:

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.

回答1:

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.



标签: c# jwt