NodeJS 如何处理json web tokens中的错误

q5lcpyga  于 11个月前  发布在  Node.js
关注(0)|答案(1)|浏览(124)

我是初学者,并试图处理jwt验证。在下面的函数中,我希望如果用户访问令牌过期,那么我会在刷新令牌的基础上生成新的访问令牌。

import { asyncHandler } from "../utils/asyncHandler.js";
import jwt from "jsonwebtoken";
import { generateAccessTokenAndRefreshToken } from "../utils/generateTokens.js";
import { User } from "../models/user.model.js";

export const isRequestAuthorized = asyncHandler(async (req, res, next) => {
  try {
    console.log("Start");
    const userAccessToken =
      req.cookies?.accessToken ||
      req.header("Authorization").replace("Bearer ", "");

    const userRefreshToken = req.cookies?.refreshToken;
    console.log(
      "Access token: " +
        userAccessToken +
        " refresh token: " +
        userRefreshToken,
    );

    if (!userAccessToken || !userRefreshToken) {
      throw new ApiError(404, "Auth Tokens missing");
    }

    const decodedAccessToken = await jwt.verify(
      userAccessToken,
      process.env.ACCESS_TOKEN_SECRET,
    );
    console.log(decodedAccessToken);
    //if access token is expired then checking refresh token and updating both token
    if (!decodedAccessToken) {
      console.log("access token is expired");
      const decodedRefreshToken = await jwt.verify(
        userRefreshToken,
        process.env.REFRESH_TOKEN_SECRET,
      );
      console.log("isRefreshTokenValid", decodedAccessToken);
      if (!decodedRefreshToken) {
        throw new ApiError(404, "Auth Tokens expired");
      }

      const { accessToken, refreshToken } =
        generateAccessTokenAndRefreshToken(decodedRefreshToken);

      const user = await user.findById(decodedRefreshToken);

      if (userRefreshToken !== user.refreshToken && user.isAdmin == false) {
        throw new ApiError(404, "UnAuthorized request");
      }

      const options = { httpOnly: true, secure: true };
      res.user = user;
      res
        .cookie("accessToken", accessToken, options)
        .cookie("refreshToken", refreshToken, options)
        .save();
      next();
    }

    const user = await User.findById(decodedAccessToken);

    if (userRefreshToken !== user.refreshToken && user.isAdmin == false) {
      throw new ApiError(404, "UnAuthorized request");
    }

    res.user = user;
    next();
  } catch (error) {
    console.log(error.message);
  }
});

字符串
我面临的错误是,当jwt正在验证我的访问令牌它结束的功能,并抛出accesstoken是过期的错误,因为我想继续我的功能,并希望在刷新令牌的基础上生成新的accessToken.请告诉我修复.

waxmsbnn

waxmsbnn1#

尝试此代码,如果在验证访问令牌时出现错误(由于过期),它会捕获错误,记录访问令牌已过期,然后继续执行使用刷新令牌刷新访问令牌的逻辑。

export const isRequestAuthorized = asyncHandler(async (req, res, next) => {
  try {
    console.log("Start");
    const userAccessToken =
      req.cookies?.accessToken ||
      req.header("Authorization").replace("Bearer ", "");

    const userRefreshToken = req.cookies?.refreshToken;
    console.log(
      "Access token: " +
        userAccessToken +
        " refresh token: " +
        userRefreshToken,
    );

    if (!userAccessToken || !userRefreshToken) {
      throw new ApiError(404, "Auth Tokens missing");
    }

    let decodedAccessToken;
    try {
      decodedAccessToken = await jwt.verify(
        userAccessToken,
        process.env.ACCESS_TOKEN_SECRET,
      );
      console.log(decodedAccessToken);
    } catch (accessTokenError) {
      console.log("Access token is expired");
      // Continue with the logic to refresh the access token
    }

    if (!decodedAccessToken) {
      const decodedRefreshToken = await jwt.verify(
        userRefreshToken,
        process.env.REFRESH_TOKEN_SECRET,
      );
      console.log("isRefreshTokenValid", decodedAccessToken);
      if (!decodedRefreshToken) {
        throw new ApiError(404, "Auth Tokens expired");
      }

      const { accessToken, refreshToken } =
        generateAccessTokenAndRefreshToken(decodedRefreshToken);

      const user = await User.findById(decodedRefreshToken);

      if (userRefreshToken !== user.refreshToken && user.isAdmin == false) {
        throw new ApiError(404, "UnAuthorized request");
      }

      const options = { httpOnly: true, secure: true };
      res.user = user;
      res
        .cookie("accessToken", accessToken, options)
        .cookie("refreshToken", refreshToken, options)
        .save();
      next();
    } else {
      const user = await User.findById(decodedAccessToken);

      if (userRefreshToken !== user.refreshToken && user.isAdmin == false) {
        throw new ApiError(404, "UnAuthorized request");
      }

      res.user = user;
      next();
    }
  } catch (error) {
    console.log(error.message);
  }
});

字符串

相关问题