我从 SonarQube 得到了一个观察结果 - 在使用令牌内容之前,始终使用
verify()
函数对 JWT 进行签名并验证它们。请注意,verify()
返回解码后的令牌值,无需使用decode()
函数。所以我必须将代码更改为以下版本。
import { HttpException, HttpStatus, Injectable, NestMiddleware } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as jwks from 'jwks-rsa';
import * as jwt from 'jsonwebtoken';
@Injectable()
export class TokenValidation implements NestMiddleware {
constructor(private readonly configService: ConfigService) { }
async use(req: any, _res: any, next: () => void) {
const authHeader = req.headers.authorization;
const token = this.extractBearerToken(authHeader);
const client = jwks({
jwksUri: this.configService.get('JWKS_URL'),
});
try {
await new Promise<void>((resolve, reject) => {
jwt.verify(token, async (header, callback) => {
client.getSigningKey(header.kid, async (err, k) => {
if (err) {
reject(new HttpException('Token has expired', HttpStatus.UNAUTHORIZED));
} else {
const key = k.getPublicKey();
callback(null, key);
resolve();
}
});
}, { algorithms: ['RS256'] });
});
next();
} catch (error) {
if (error instanceof jwt.JsonWebTokenError) {
throw new HttpException('Token verification has failed', HttpStatus.UNAUTHORIZED);
} else {
throw new HttpException('Internal server error', HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
}
发送不记名令牌时,我收到
JsonWebTokenError: verify must be called asynchronous if secret or public key is provided as a callback
。我哪里错了?请求社区的帮助。
陷入同样的困境,您能找到解决方案吗?