使用 nest.js jwt 不断收到内部服务器错误
keep getting internal server error with nest.js jwt
我正在使用 Nest.js JWT 来保护我的资源,但是当我不提供令牌或令牌无效时,我不断收到内部服务器错误,而不是获取未授权异常,如以下 jwt 策略文件所示
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy } from "passport-jwt";
import { AuthService } from "../services/auth.service";
export interface JwtPayload {
user: string,
refreshToken: boolean
}
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
private authService: AuthService
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.SECURITY_KEY,
});
}
async validate(payload: JwtPayload) {
// prevent passing refresh token as access token
if (payload.refreshToken) {
throw new UnauthorizedException('Access Token Only');
}
const user = await this.authService.getUserFromJwtPayload(payload.user);
if (!user) {
throw new UnauthorizedException('Invalid User');
}
// checks if user logged out
if (!user.refreshToken) {
throw new UnauthorizedException('You have logged out');
}
return user;
}
}
请帮助我,我不知道为什么我一直收到内部服务器错误,是否有任何地方遗漏或我必须做些什么。
我认为这个过程出了问题:
const user = await this.authService.getUserFromJwtPayload(payload.user);
所以它不会涉及您检查您是否拥有有效用户或 refreshToken 的部分。我认为,如果您删除两个 if 语句,您仍然会收到内部服务器错误。
如果您遇到内部服务器错误,请确保您运行执行以下命令npm install @nestjs/jwt @nestjs/passport @nestjs/passport-jwt passport passport-jwt
我正在使用 Nest.js JWT 来保护我的资源,但是当我不提供令牌或令牌无效时,我不断收到内部服务器错误,而不是获取未授权异常,如以下 jwt 策略文件所示
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy } from "passport-jwt";
import { AuthService } from "../services/auth.service";
export interface JwtPayload {
user: string,
refreshToken: boolean
}
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
private authService: AuthService
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.SECURITY_KEY,
});
}
async validate(payload: JwtPayload) {
// prevent passing refresh token as access token
if (payload.refreshToken) {
throw new UnauthorizedException('Access Token Only');
}
const user = await this.authService.getUserFromJwtPayload(payload.user);
if (!user) {
throw new UnauthorizedException('Invalid User');
}
// checks if user logged out
if (!user.refreshToken) {
throw new UnauthorizedException('You have logged out');
}
return user;
}
}
请帮助我,我不知道为什么我一直收到内部服务器错误,是否有任何地方遗漏或我必须做些什么。
我认为这个过程出了问题:
const user = await this.authService.getUserFromJwtPayload(payload.user);
所以它不会涉及您检查您是否拥有有效用户或 refreshToken 的部分。我认为,如果您删除两个 if 语句,您仍然会收到内部服务器错误。
如果您遇到内部服务器错误,请确保您运行执行以下命令npm install @nestjs/jwt @nestjs/passport @nestjs/passport-jwt passport passport-jwt