首页 > 解决方案 > 为什么验证函数中的令牌参数在 jwt 身份验证中显示错误?

问题描述

我正在尝试进行 jwt 身份验证,并且在验证功能上遇到这样的错误。

没有重载匹配此调用。重载 1 of 3, '(token: string, secretOrPublicKey: Secret, options?: VerifyOptions | undefined): string | 对象',给出了以下错误。'string | 类型的参数 字符串[] | undefined' 不能分配给'string' 类型的参数。类型“未定义”不可分配给类型“字符串”。Overload 2 of 3, '(token: string, secretOrPublicKey: Secret | GetPublicKeyOrSecret, callback?: VerifyCallback | undefined): void',给出以下错误。

import { NextFunction, Request, Response } from "express";
import jwt from "jsonwebtoken";
import config from "../config/default"

var authorization = function (req:Request, res:Response, next:NextFunction) {
    var token = req.headers['x-access-token'];
    var msg = {auth: false, message: 'No token provided.'};

    if (!token) res.status(500).send(msg);

    jwt.verify(token, config.token.secret, function (err) {
        var msg = {auth: false, message: 'Failed to authenticate token.'};
        if (err) res.status(500).send(msg);
        next();
    });
}

module.exports = authorization;

标签: node.jstypescriptexpressjwtexpress-jwt

解决方案


问题是req.headers返回类型的值string | string[] | undefined。并且您正试图将它作为参数传递给string在该位置期望类型的函数。因此错误。

您的代码存在一些问题,您必须解决它才能修复它:

  • 函数执行后if (!token) res.status(500).send(msg)不会停止。它将进行到jwt.verify. 虽然它不会通过带有虚假令牌的令牌检查,但无论如何它都会运行验证功能。此条件不会缩小类型。
declare const n: number | null

if (!n) {
  console.log('0, NaN or null')
} else {
  type N = typeof n // N ~ number
}

if (!n) console.log('0, NaN or null')

type M = typeof n // M ~ number | null

游乐场链接

  • token可能是一个字符串数组

为了使您的代码能够进行类型检查并正常工作,您必须将类型缩小tokenstring

import { NextFunction, Request, Response } from "express";
import jwt, { VerifyErrors } from "jsonwebtoken";
import config from "../config/default"

var authorization = function (req:Request, res:Response, next:NextFunction) {
    var token = req.headers['x-access-token'];
    var msg = {auth: false, message: 'No token provided.'};

    // check whether `token` is an array and get the first element
    // narrows the type to `string | undefined`
    if (Array.isArray(token)) token = token[0];

    // narrows the type to `string`
    if (!token) {
      res.status(500).send(msg);
      // return early and prevent execution of the underlying middlewares
      return next(false); 
    }

    jwt.verify(token, config.token.secret, function (err: VerifyErrors | null) {
        var msg = {auth: false, message: 'Failed to authenticate token.'};
        if (err) res.status(500).send(msg);
        next();
    });
}

module.exports = authorization;

推荐阅读