Nodejs Nestjs插件passport-jwt实现JWT认证的使用

Nodejs Nestjs插件passport-jwt实现JWT认证的使用
passport-jwt 是一个流行的 Node.js 认证中间件,可以与 NestJS 一起使用来实现 JWT(JSON Web Token)认证。下面是使用 passport-jwt 实现 JWT 认证的基本步骤。

安装依赖

首先,你需要安装必要的依赖包:

npm install @nestjs/passport passport passport-jwt @nestjs/jwt

配置 JWT 策略

在你的 NestJS 应用中创建一个 JWT 策略文件,例如 jwt.strategy.ts:

import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: process.env.JWT_SECRET,
    });
  }

  async validate(payload: any) {
    return { userId: payload.sub, username: payload.username };
  }
}

在这个策略中,我们配置了从请求头中提取 JWT,并使用环境变量中的密钥进行验证。validate 方法用于验证 JWT 并返回用户信息。

注册策略

在你的模块文件(例如 auth.module.ts)中注册策略:

import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { JwtStrategy } from './jwt.strategy';

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      secret: process.env.JWT_SECRET,
      signOptions: { expiresIn: '60m' },
    }),
  ],
  providers: [JwtStrategy],
  exports: [PassportModule, JwtModule],
})
export class AuthModule {}

创建控制器

创建一个控制器来处理登录和验证请求。例如 auth.controller.ts:

import { Controller, Post, Body, Request, UseGuards } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LocalAuthGuard } from './local-auth.guard';
import { JwtAuthGuard } from './jwt-auth.guard';

@Controller('auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @UseGuards(LocalAuthGuard)
  @Post('login')
  async login(@Request() req) {
    return this.authService.login(req.user);
  }

  @UseGuards(JwtAuthGuard)
  @Post('profile')
  getProfile(@Request() req) {
    return req.user;
  }
}

创建服务

创建一个服务来处理生成和验证 JWT。例如 auth.service.ts:

import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(private jwtService: JwtService) {}

  login(user: any) {
    const payload = { username: user.username, sub: user.userId };
    return {
      access_token: this.jwtService.sign(payload),
    };
  }
}

创建 Guard

创建一个 Guard 来保护路由不被未授权的访问。例如 jwt-auth.guard.ts:

import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}

环境变量

确保在你的项目根目录下有一个 .env 文件来存储敏感信息,如 JWT 密钥:

JWT_SECRET=your_jwt_secret

使用

现在你可以使用这些组件来保护你的 API 路由。例如,你可以通过 POST 请求发送用户名和密码来获取 JWT,然后在其他需要身份验证的路由中使用这个 JWT。

以上就是使用 passport-jwt 和 NestJS 实现 JWT 认证的基本步骤。希望这对你有所帮助!


3 回复

当然可以!首先,确保你已经安装了passport-jwt[@nestjs](/user/nestjs)/passport等依赖。然后,在你的模块中配置它。这里有个小故事:

假设你正在做一个魔法学校项目,每个巫师都需要通过“魔法令牌”来证明自己的身份。

  1. 引入魔法材料(安装依赖):

    npm install [@nestjs](/user/nestjs)/passport passport passport-jwt
    
  2. 创建魔法防御术(配置策略): 在你的服务或一个单独的文件中,创建一个魔法防御术(策略):

    import { ExtractJwt, Strategy } from 'passport-jwt';
    import { PassportStrategy } from '[@nestjs](/user/nestjs)/passport';
    
    export class MagicDefenseStrategy extends PassportStrategy(Strategy) {
      constructor() {
        super({
          jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
          ignoreExpiration: false,
          secretOrKey: 'your_secret_key', // 这里应该是你的魔法学校的秘密
        });
      }
    
      async validate(payload: any) {
        return { userId: payload.sub, username: payload.username };
      }
    }
    
  3. 设置魔法仪式(应用策略): 在你的控制器或模块中使用这个策略:

    import { AuthService } from './auth.service';
    import { MagicDefenseStrategy } from './magic-defense.strategy';
    
    [@UseGuards](/user/UseGuards)(AuthGuard('jwt'))
    [@Controller](/user/Controller)('wizard')
    export class WizardController {
      constructor(private authService: AuthService) {}
    
      @Get()
      getWizardInfo(@Request() req) {
        return req.user;
      }
    }
    

现在,每当巫师想要访问需要魔法令牌保护的信息时,他们必须通过这个魔法防御术的考验。希望这能帮助到你,让代码像魔法一样运行起来吧!


在NestJS中使用passport-jwt插件来实现JWT(JSON Web Token)认证是一种常见的做法。下面将详细介绍如何设置和使用passport-jwt来实现JWT认证。

1. 安装必要的依赖

首先,确保安装了以下依赖包:

npm install @nestjs/passport passport passport-jwt @types/passport-jwt

2. 配置JWT策略

创建一个文件(例如jwt.strategy.ts),在这个文件中定义你的JWT策略。

import { PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { Injectable } from '@nestjs/common';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
    constructor() {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            ignoreExpiration: false,
            secretOrKey: process.env.JWT_SECRET, // 从环境变量获取密钥
        });
    }

    async validate(payload: any) {
        return { userId: payload.sub, username: payload.username };
    }
}

3. 创建控制器和方法来生成JWT

接下来,在你的服务或控制器中添加一个方法来生成JWT令牌。

import { Injectable } from '@nestjs/common';
import * as jwt from 'jsonwebtoken';

@Injectable()
export class AuthService {
    signToken(userId: string, username: string): string {
        const payload = { sub: userId, username };
        return jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '1h' });
    }
}

4. 保护路由

最后,在需要保护的路由上应用@UseGuards(AuthGuard('jwt'))装饰器。

import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from './auth.service';

@Controller()
export class AppController {
    constructor(private readonly authService: AuthService) {}

    @Get('protected')
    @UseGuards(AuthGuard('jwt'))
    getProtectedData() {
        return { message: 'This is a protected route.' };
    }
}

5. 环境变量配置

确保在你的项目根目录下有一个.env文件,并设置JWT_SECRET等必要的环境变量。

JWT_SECRET=your_jwt_secret_key

总结

以上步骤展示了如何在NestJS应用中设置和使用passport-jwt插件来实现JWT认证。这个流程包括了安装必要的依赖、配置JWT策略、生成JWT令牌以及保护特定路由。通过这些步骤,你可以为你的NestJS应用添加基本的认证功能。

使用passport-jwt在NestJS中实现JWT认证,首先安装@nestjs/passport, passport, 和passport-jwt包。配置PassportModule并创建一个策略类来处理JWT验证逻辑。

import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: 'your-secret-key',
    });
  }

  async validate(payload: any) {
    return { userId: payload.sub, username: payload.username };
  }
}

然后,在控制器中应用此策略进行保护:

@UseGuards(AuthGuard('jwt'))
@Controller()
export class AppController {}

确保设置好环境变量存储密钥,并且客户端发送请求时包含正确的Authorization头部信息。

回到顶部