为什么验证函数中的 token 参数在 jwt 验证中显示错误?

why the token parameter in verify function is showing error in jwt authentitcation?

I am trying to do jwt authentication and i am getting error like this on verify function.

No overload matches this call. Overload 1 of 3, '(token: string, secretOrPublicKey: Secret, options?: VerifyOptions | undefined): string | object', gave the following error. Argument of type 'string | string[] | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'. Overload 2 of 3, '(token: string, secretOrPublicKey: Secret | GetPublicKeyOrSecret, callback?: VerifyCallback | undefined): void', gave the following error.

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;

问题是 req.headers returns 类型 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

playground link

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

为了您的代码能够进行类型检查并正常工作,您必须 narrowtoken 的类型更改为 string:

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;