小编Syx*_*kno的帖子

JwtModule.registerAsync 在 NestJS 中不起作用

我正在开发一个 NestJS 项目,我需要使用 JWT 进行.env配置。它生成令牌,但当尝试访问安全 url(带有授权标头)时,它仅返回未经授权的消息。

jwt.strategy.ts

import { Injectable, UnauthorizedException, Logger } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { AuthService } from './auth.service';
import { JwtPayload } from './interfaces/jwt-payload.interface';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {

    constructor(private readonly authService: AuthService) {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            secretOrKey: process.env.JWT_SECRET_KEY,
        });
    }

    async validate(payload: JwtPayload) {
        const user = await this.authService.validateUser(payload);
        if (!user) {
            throw new UnauthorizedException();
        }

        return user;
    } …
Run Code Online (Sandbox Code Playgroud)

javascript node.js jwt nestjs dotenv

4
推荐指数
1
解决办法
1万
查看次数

标签 统计

dotenv ×1

javascript ×1

jwt ×1

nestjs ×1

node.js ×1