无法使用RS256验证JWT-无效算法

时间:2018-11-02 17:42:10

标签: javascript node.js jwt

我正在尝试将JWT身份验证从秘密短语转移到RS256

下面是示例代码:

import fs from 'fs'
import jwt from 'jsonwebtoken'

const private_key = fs.readFileSync('private.key')
const public_key = fs.readFileSync('public.pem')

const token = jwt.sign({
    some: 'payload'
}, private_key, { algorithm: 'RS256' })

const verified = jwt.verify(token, public_key)

这是我的公钥格式:

-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAyLVWMJHRJ0VRPiyhjvPJTwpgNkMd4jjvUxEfy54COanbrL+GeOVd
NB2YooopYzgJJZyVhHSD+GwyH7WTvsItwNkfMiZKmjUIEA9dIfcbmHNXtfXraiSh
aTSO7NIREGzGQjBfzRGNeWpR83P+ffE5H0gfi9FFJlvV8QSLSSXJNMXVFAga//fb
uT/CYLg29bzEBtNSdgTHNrbwSvYzGFDOHNChDelX6fp34JMhtb6UNh6cIqhURclK
reQHz2oDcBaXnCAHjvC8p/IoG8xV2Ws5gK6bVW7h0EP5XoaUVHVpjPv5TDFz+veR
/lkKdowQU74E5oyei1WzDXSTusCR9gKIcQIDAQAB
-----END RSA PUBLIC KEY-----

我遇到以下错误:

JsonWebTokenError: invalid algorithm

当我尝试在jwt.io上进行验证时,令牌已成功签名。

1 个答案:

答案 0 :(得分:0)

尝试一下:

var fs = require('fs')
var jwt = require('jsonwebtoken')

const private_key = fs.readFileSync('private.key', 'utf8')
const public_key = fs.readFileSync('public.pem', 'utf8')


const token = jwt.sign({
    some: 'payload'
}, private_key, { algorithm: 'RS256' })

const verified = jwt.verify(token, public_key, { algorithms: 'RS256'})

私钥:(private.key)

-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDCDzF83j+imr1t2fNtfT4Fusm3LJAzFK49xK3bepARl2gcKKNm
YJI6svZ8mznkoDp1uCuwyBKVIkRfrGAd1FuuVrzMi0kairWGz71FHbcubKy/6AOG
caONmk0K1DjS4dIzJLmIeUpv2jrtIctGDt2tXg4OQ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