我正在尝试编写一个服务,该服务将采用 JWT 令牌并使用 JWKS JSON 格式的公钥对其进行验证。我相信我可以抓住钥匙并将其转换为
KeyObject
(不知道这是否有必要),但我不太清楚如何将其转换为verifyAsync
需要的任何格式,我猜是PEM 格式。这是我到目前为止的代码:
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { KeyObject, createPublicKey } from 'crypto';
@Injectable()
export class TokenValidationService {
constructor(
private jwtService: JwtService
) { }
async validate(token: string): Promise<any | boolean> {
const jwt = this.jwtService.decode(token);
if (!jwt) {
return false;
}
const jwks: Response = await fetch('https://xxxxxx.auth0.com/.well-known/jwks.json');
const jwksJson = await jwks.json();
const key: KeyObject = createPublicKey({
key: jwksJson.keys[0],
format: 'jwk'
})
// TODO: Somehow convert this KeyObject into a string that verifyAsync accepts
await this.jwtService.verifyAsync(token, {
algorithms: ['RS256'],
publicKey: myKeyString
})
return jwt;
}
}
如有任何帮助,我们将不胜感激。
好吧,我想我明白了。如果有更好的方法来做到这一点,我仍然感兴趣。
const key: KeyObject = createPublicKey({
key: jwksJson.keys[0],
format: 'jwk'
})
const exportedKey: string = key.export({ type: 'pkcs1', format: 'pem' }).toString();
const verifiedJwt = await this.jwtService.verifyAsync(token, {
algorithms: ['RS256'],
publicKey: exportedKey,
ignoreExpiration: true
})
为什么不使用像
jwks-rsa
这样的东西?
示例取自:https://www.npmjs.com/package/jsonwebtoken
var jwksClient = require('jwks-rsa');
var client = jwksClient({
jwksUri: 'https://sandrino.auth0.com/.well-known/jwks.json'
});
function getKey(header, callback){
client.getSigningKey(header.kid, function(err, key) {
var signingKey = key.publicKey || key.rsaPublicKey;
callback(null, signingKey);
});
}
jwt.verify(token, getKey, options, function(err, decoded) {
console.log(decoded.foo) // bar
});