Nodejs验证来自.net的jwt令牌失败

时间:2017-02-06 02:35:58

标签: c# node.js jwt

我通过这个C#代码(使用System.IdentityModel.Tokens.Jwt)从.net创建令牌:

var keybytes = Convert.FromBase64String("MYCUSTOMCODELONGMOD4NEEDBEZE");
var signingCredentials = new SigningCredentials(

new InMemorySymmetricSecurityKey(keybytes),
SecurityAlgorithms.HmacSha256Signature,
SecurityAlgorithms.Sha256Digest);
var nbf = DateTime.UtcNow.AddDays(-100);
var exp = DateTime.UtcNow.AddDays(100);
var payload = new JwtPayload(null, "", new List<Claim>(), nbf, exp);
var user = new Dictionary<string, object>();
user.Add("userId", "1");

payload.Add("user", user);
payload.Add("success", true);
var jwtToken = new JwtSecurityToken(new JwtHeader(signingCredentials), payload);
var jwtTokenHandler = new JwtSecurityTokenHandler();
var resultToken = jwtTokenHandler.WriteToken(jwtToken);

我将resultToken发送到nodejs并使用以下代码验证它(使用jsonwebtoken库):

var jwt    = require('jsonwebtoken');

var result = jwt.verify(
  resultToken,
  new Buffer('MYCUSTOMCODELONGMOD4NEEDBEZE').toString('base64'),
  { algorithms: ['HS256'] },
  function(err, decoded) {
    if (err) {
    console.log('decode token failed with error: '+ JSON.stringify(err));
    }
  }
);

我收到错误:签名无效。 resultToken内容:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0OTQ4MTMxMTUsIm5iZiI6MTQ3NzUzMzExNSwidXNlciI6eyJ1c2VySWQiOiIxIn0sInN1Y2Nlc3MiOnRydWV9.4bjYyIUFMouz-ctFyxXkJ_QcJJQofCEFffUuazWFjGw

我在jwt.io上使用以上签名(MYCUSTOMCODELONGMOD4NEEDBEZE)进行了调试,并检查了秘密base64编码,它没问题。

我尝试过一种没有base64编码的签名,在C#代码中使用keybytes进行编码:

var keybytes = Encoding.UTF8.GetBytes("MYCUSTOMCODELONGMOD4NEEDBEZE");

它在nodejs中验证成功。所以我认为在验证base64编码签名时问题来自我的nodejs代码。在验证令牌或某事时,我是否错过了一些选项?

1 个答案:

答案 0 :(得分:2)

我不知道你做了什么,但是这个片段对我来说是上面提供的令牌。

var jwt = require('jwt-simple')

var secret = new Buffer('MYCUSTOMCODELONGMOD4NEEDBEZE').toString('base64')
var token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0OTQ4MTMxMTUsIm5iZiI6MTQ3NzUzMzExNSwidXNlciI6eyJ1c2VySWQiOiIxIn0sInN1Y2Nlc3MiOnRydWV9.4bjYyIUFMouz-ctFyxXkJ_QcJJQofCEFffUuazWFjGw'

var decoded = jwt.decode(token, secret)
console.log(decoded)

输出:

❯ node jwt.js
{ exp: 1494813115,
  nbf: 1477533115,
  user: { userId: '1' },
  success: true }    

使用jsonwebtoken库

// var jwt = require('jwt-simple')

var jwt = require('jsonwebtoken');
var secret = Buffer.from('MYCUSTOMCODELONGMOD4NEEDBEZE', 'base64')
var token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0OTQ4MTMxMTUsIm5iZiI6MTQ3NzUzMzExNSwidXNlciI6eyJ1c2VySWQiOiIxIn0sInN1Y2Nlc3MiOnRydWV9.4bjYyIUFMouz-ctFyxXkJ_QcJJQofCEFffUuazWFjGw'

jwt.verify(token, secret, { algorithms: ['HS256'] }, function(err, decoded) {
    if (err) {
        console.log(err)
    } else {
        console.log(decoded)    
    }  
})

再次仍然正常工作。

我能看到的唯一区别就是秘密。