我正在尝试在 jwt.strategy.ts 的 validate 函数中验证令牌是否有效如果 JWT 不记名标头身份验证令牌无效,则会引发异常否则,将返回 JWT 有效负载。更具体地说,Passport 将创建一个“快速 HTTP 请求对象上的 user" 属性,并将此处返回的任何内容分配给 req.user
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import * as dotenv from 'dotenv';
dotenv.config();
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreException: true,
secretOrKey: process.env.JWT_SECRET,
});
}
@param payload
async validate(payload: any) {
const isAuthorized = this.authConfig.roles.some((role) => payload.role?.includes(role));
if(!isAuthorized) {
Logger.error(`Unauthorized: Invalid role`);
throw new UnauthorizedException();
}
console.log('validate()',payload);
return { userId: payload.sub, username: payload.username };
}
}
jwt.strategy.ts
import { Body, Controller, Post } from '@nestjs/common';
import { AuthDto } from './dtos/auth.dto';
import { AuthService } from './auth.service';
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}
/**
* API endpoint handler for user login
* @param dto
*/
@Post('/login')
login(@Body() dto: AuthDto) {
console.log('hi')
this.authService.login(dto)
}
}
身份验证控制器.ts
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtStrategy } from './strategies/jwt.strategy';
import { MongooseModule } from '@nestjs/mongoose';
import { User, UserSchema } from '@sp/schemas';
import { UserService } from '../user/user.service';
import { UserController } from '../user/user.controller';
import * as dotenv from 'dotenv';
dotenv.config();
@Module({
imports: [
JwtModule.register({
secret: process.env.JWT_SECRET,
signOptions: { expiresIn: '5m' },
}),
MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy, UserService],
})
export class AuthModule {}
auth.module.ts
import { HttpException, Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
const jwt = require("jsonwebtoken");
import { AuthDto } from './dtos/auth.dto';
import { UserService } from '../user/user.service';
@Injectable()
export class AuthService {
constructor(private jwtService: JwtService, private Users: UserService) {}
/**
* Determines if the user credentials provided are correct
* @param dto
*/
async login(dto: AuthDto) {
this.Users.findByEmail(dto.email)
.then((user)=>{
if(!user){
throw new HttpException("not autheroized",401)
}
else{
if(dto.password == user.password){
const payload = { sub: user.giuEmail ,username: user.name};
console.log(payload);
console.log(this.jwtService.sign(payload));
return {
access_token: this.jwtService.sign(payload),
};
}
}
})
}
}
身份验证服务.ts