Cannot read properties of undefined (reading 'verify') at JwtAuthGuard.canActivate

问题描述 投票:0回答:0

我每次使用 jwt 令牌检查 getUsers 路由时都会收到此错误

这是我的 jwtAuth.guards.ts 文件

import { Injectable, ExecutionContext, CanActivate } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';
import { JwtService } from '@nestjs/jwt';
import { User } from 'src/users/user.entity';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
    constructor(private jwtService: JwtService) {
        console.log(jwtService);
        super();
    }

    canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
        const req = context.switchToHttp().getRequest();
        const token = req.headers.authorization?.split(' ')[1];
        if (token) {
            const user = this.jwtService.verify<User>(token);
            req.user = user;
        }
        return super.canActivate(context);
    }
}

@Injectable()
export class RolesGuard implements CanActivate {
    constructor(private readonly reflector: Reflector) { }

    canActivate(context: ExecutionContext): boolean {
        const requiredRoles = this.reflector.getAllAndOverride<string[]>('roles', [
            context.getHandler(),
            context.getClass(),
        ]);
        if (!requiredRoles) {
            return true;
        }
        const { user } = context.switchToHttp().getRequest();
        return requiredRoles.some(role => user.roles?.includes(role));
    }
}

这是我的 auth.module.ts

import { Module } from "@nestjs/common";
import { AuthService } from "./auth.service";
import { AuthController } from "./auth.controller";
import { JwtModule } from "@nestjs/jwt/dist";
import { UserModule } from "src/users/user.module";
import { UserService } from "src/users/user.service";
import { JwtConfig } from "src/config/jwt.config";
import { LocalStrategy } from "./strategies/local.strategy";
import { PassportModule } from "@nestjs/passport";
import { JwtStrategy } from "./strategies/jwt.strategy";

@Module({
    imports: [
        PassportModule,
        JwtModule.registerAsync(JwtConfig),
        UserModule,
    ],
    controllers: [AuthController],
    providers: [AuthService, UserService, LocalStrategy, JwtStrategy]
})
export class AuthModule { }

我尝试记录 JwtConfig 文件,它工作正常 这是 user.service.ts 文件

import { Injectable, NotFoundException } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { User } from './user.entity';
import { Repository } from "typeorm";
import * as bcrypt from 'bcrypt';
import { CreateUserDto } from "src/auth/dto/create-user.dto";
import { UpdateUserDto } from "src/auth/dto/update-user.dto";
import { Role } from "./role.entity";
@Injectable()
export class UserService {
    constructor(
        @InjectRepository(User)
        private readonly userRepository: Repository<User>,
        @InjectRepository(Role)
        private readonly roleRepository: Repository<Role>,
    ) { }

    //* FIND BY EMAIL
    async findByEmail(email: string): Promise<User | undefined> {
        return this.userRepository.findOne({ where: { email } });
    }

    //*1 GET ALL USERS DATA FROM DATABASE
    async findAll(): Promise<User[]> {
        return await this.userRepository.find();
    }

    //*2 GET SINGLE USER FROM DATABASE
    async findOne(id: string): Promise<User> {
        const user = await this.userRepository.findOne({ where: { id } });
        if (!user) {
            throw new NotFoundException(`User not found`);
        }
        return user;
    }

    //*3 CREATE A USER IN DATABASE
    async create(createUserDto: CreateUserDto): Promise<User> {
        const { username, email, password, roleId, pfxPath } = createUserDto;

        // find all roles by provided IDs
        const foundRoles = await this.roleRepository.findBy({ id: roleId });
        if (foundRoles.length !== roleId.length) {
            throw new NotFoundException('Invalid role(s) provided');
        }

        const user = new User();
        user.username = username;
        user.email = email;
        const saltOrRounds = 10;
        const hashedPassword = await bcrypt.hash(password, saltOrRounds);
        user.password = hashedPassword;
        user.roles = foundRoles;
        user.pfxPath = pfxPath;

        return await this.userRepository.save(user);
    }

    //*4 UPDATE USER
    async update(id: string, updateUserDto: UpdateUserDto): Promise<User> {
        const { username, email, password, roleId, pfxPath } = updateUserDto;

        // find the user to update
        const user = await this.userRepository.findOne({ where: { id } });
        if (!user) {
            throw new NotFoundException('User not found');
        }

        // update properties
        user.username = username || user.username;
        user.email = email || user.email;
        const saltOrRounds = 10;
        const hashedPassword = await bcrypt.hash(password, saltOrRounds);
        user.password = hashedPassword || user.password;
        user.pfxPath = pfxPath || user.pfxPath;

        if (roleId) {
            // find all roles by provided IDs
            const foundRoles = await this.roleRepository.findBy({ id: roleId });
            if (foundRoles.length !== roleId.length) {
                throw new NotFoundException('Invalid role(s) provided');
            }
            user.roles = foundRoles;
        }

        return await this.userRepository.save(user);
    }


    //*5 DELETE A USER
    async remove(id: string): Promise<void> {
        const user = await this.userRepository.findOne({ where: { id } });
        await this.userRepository.remove(user);
    }


} 

我已经尝试从 jwtAuth.guards.ts 记录 jwtService 并且它在运行时之间显示未定义...

authentication jwt nestjs token passport.js
© www.soinside.com 2019 - 2024. All rights reserved.