Jwt-Dotnet没有生成有效的令牌

时间:2017-06-21 16:02:58

标签: c# encryption jwt

我正在尝试使用C#生成有效的JWT令牌,我的代码是

        string secret = "6ASu2c8V/zF..........******"; // base64encoded
        var payload = new Dictionary<string, string>
        {
            {"iss", "http://webapi.one*******"},
            {"exp", "1498140965"},
            {"aud", "ONE****"},
            {"playauth", "Ygo2s********"}
        };

        IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
        IJsonSerializer serializer = new JsonNetSerializer();
        IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
        IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

        var token = encoder.Encode(payload,secret);
        return token;

当我运行代码时,它会生成令牌

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vd2ViYXBpLm9uZXJlZWwubmV0IiwiZXhwIjoxNDk4MTQwOTY1LCJhdWQiOiJPTkVSRUVMIiwicGxheWF1dGgiOiJZZ28yc2Nob29sQG5pdGU5JCJ9.MuWc9tebE8IZFOIFsh2E_JP-UFQl4UZ9kTBG19_REnM

但此令牌在https://jwt.io/上显示无效签名,并且我在验证签名上使用了正确的密钥

1 个答案:

答案 0 :(得分:2)

我终于解决了它。我将我的based64编码令牌转换为字节数组,它完美地工作。在这里,新代码:

        byte[] secret = Convert.FromBase64String("6ASu2c8V/zF*******");

        var payload = new Dictionary<string, object>
        {
            {"iss", "http****"},
            {"aud", "O***"},
            {"exp", expiryDate},
            {"nbf", createdDate}
        };

        IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
        IJsonSerializer serializer = new JsonNetSerializer();
        IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
        IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

        var token = encoder.Encode(payload, secret);
        return token;