如何使用jwks-rsa库获取令牌的关键孩子(密钥ID)

时间:2019-07-09 18:08:04

标签: node.js express jwt

我有一些用于验证令牌的密钥ID,但是它是硬编码的,我不希望这样。 我正在使用jwks-rsa库从API端点获取密钥并破解令牌以进行验证,但是获取是在jwks-rsa客户端对象的option属性中完成的,因此我不确定如何去做关于将获取的“ kid”值存储在变量中。很难解释,所以我将显示一些代码。

'use strict'

require('dotenv').config()
const jwt = require('jsonwebtoken')
const jwks = require('jwks-rsa')

const TOKEN_SECRET = 'someweirdtokenstring'

function (request, response, next) {
    const client = jwks({
        jwksUri: process.env.TOKEN_KEY_PUBLIC //this is the API endpoint; responds with a json key
    })
    const kid = 'something' //I don't want to hardcode this
    client.getSigningKey(kid, (error, key) => {
        if (error) throw error
        const signingKey = key.publicKey || key.rsaPublicKey
        const token = TOKEN_SECRET
        if (!token) return response.status(401).send('Access denied')
        try {
            const verified = jwt.verify(token, signingKey, { algorithms: ['RS256'] })
            request.user = verified
            next()
        } catch (error) {
            response.status(400).send({ message: error.message, stack: error.stack })
        }
    })
}

编辑:这不是超级干净的代码,但这不是重点。

1 个答案:

答案 0 :(得分:0)

IMO,您应该在JWT的标头中创建带有kid的JWT。只需解码即可读取标头。

这是小片段,

'use strict'

require('dotenv').config()
const jwt = require('jsonwebtoken')
const jwks = require('jwks-rsa')

const TOKEN_SECRET = 'someweirdtokenstring'

function (request, response, next) {
    const client = jwks({
        jwksUri: process.env.TOKEN_KEY_PUBLIC //this is the API endpoint; responds with a json key
    })
    var decoded = jwt.decode(token, {complete: true});
    const kid = decoded.kid
    client.getSigningKey(kid, (error, key) => {
        if (error) throw error
        const signingKey = key.publicKey || key.rsaPublicKey
        const token = TOKEN_SECRET
        if (!token) return response.status(401).send('Access denied')
        try {
            const verified = jwt.verify(token, signingKey, { algorithms: ['RS256'] })
            request.user = verified
            next()
        } catch (error) {
            response.status(400).send({ message: error.message, stack: error.stack })
        }
    })
}