我這個C#代碼(與System.IdentityModel.Tokens.Jwt)從.NET創建令牌:驗證的NodeJS 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編碼的檢查,它的確定。
我已經嘗試了簽名,而不在C#代碼換款keybytes
base64編碼:
var keybytes = Encoding.UTF8.GetBytes("MYCUSTOMCODELONGMOD4NEEDBEZE");
而且它成功的NodeJS驗證。所以我認爲在驗證base64編碼簽名時,問題來自我的nodejs代碼。驗證令牌或某些東西時,我是否錯過了一些選項?
請檢查此[https://runkit.com/589803649a353c0015f87d57/589803649a353c0015f87d58/branches/master](https://runkit.com/589803649a353c0015f87d57/589803649a353c0015f87d58/branches/master)和它的工作的罰款。 – Thennarasan