Nodejs Nestjs JWT认证插件@nestjs/jwt的使用

Nodejs Nestjs JWT认证插件@nestjs/jwt的使用
在NestJS中使用[@nestjs](/user/nestjs)/jwt插件进行JWT(JSON Web Token)认证是一个常见的需求。下面将详细解释如何设置和使用这个插件。

1. 安装依赖

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

npm install [@nestjs](/user/nestjs)/jwt [@nestjs](/user/nestjs)/passport passport passport-jwt
npm install --save-dev @types/passport-jwt

2. 配置模块

在你的应用程序中,你需要配置一个模块来处理JWT认证。这里假设你已经有一个模块,比如AuthModule

2.1 在AuthModule中配置JWT策略

import { Module } from '[@nestjs](/user/nestjs)/common';
import { JwtModule } from '[@nestjs](/user/nestjs)/jwt';
import { PassportModule } from '[@nestjs](/user/nestjs)/passport';

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      secret: 'your-secret-key', // 请替换为安全的密钥
      signOptions: { expiresIn: '60m' }, // 设置token过期时间
    }),
  ],
  providers: [],
  exports: [PassportModule, JwtModule],
})
export class AuthModule {}

3. 创建认证服务

接下来,创建一个服务来处理用户认证逻辑,包括生成和验证JWT。

3.1 创建AuthService

import { Injectable } from '[@nestjs](/user/nestjs)/common';
import * as bcrypt from 'bcrypt';
import { JwtService } from '[@nestjs](/user/nestjs)/jwt';

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

  async validateUser(username: string, pass: string): Promise<any> {
    const user = await this.findUserByUsername(username);
    if (user && await bcrypt.compare(pass, user.password)) {
      const { password, ...result } = user;
      return result;
    }
    return null;
  }

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

  private async findUserByUsername(username: string): Promise<any> {
    // 这里应该是一个实际的数据库查询,返回用户对象
    // 示例:return await this.usersRepository.findOne({ username });
    return { userId: 1, username, password: 'hashed-password' }; // 假数据
  }
}

4. 创建控制器

最后,创建一个控制器来处理HTTP请求,如登录和获取令牌。

4.1 创建AuthController

import { Controller, Post, Body } from '[@nestjs](/user/nestjs)/common';
import { AuthService } from './auth.service';

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

  @Post('login')
  async login(@Body() loginDto: { username: string; password: string }) {
    const user = await this.authService.validateUser(loginDto.username, loginDto.password);
    if (!user) {
      throw new UnauthorizedException();
    }
    return this.authService.login(user);
  }
}

5. 使用Guard保护路由

为了保护特定的路由,你可以使用@UseGuards(AuthGuard('jwt'))装饰器。

import { Controller, Get, UseGuards } from '[@nestjs](/user/nestjs)/common';
import { AuthGuard } from '[@nestjs](/user/nestjs)/passport';

@Controller('profile')
export class ProfileController {
  @Get()
  @UseGuards(AuthGuard('jwt'))
  getProfile() {
    return { message: 'This is your profile.' };
  }
}

以上就是如何在NestJS中使用[@nestjs](/user/nestjs)/jwt进行JWT认证的基本步骤。希望这对你有所帮助!


3 回复

当然,让我们用一点幽默来探讨这个话题!

想象一下,你正在构建一个超级英雄应用,每个英雄都需要通过@nestjs/jwt来证明自己的身份。这就好比是让他们通过跳过月球来证明自己是真正的超能力者!

首先,你需要安装[@nestjs](/user/nestjs)/jwtjsonwebtoken

npm install [@nestjs](/user/nestjs)/jwt jsonwebtoken

然后,在你的模块中配置它,就像给你的超级英雄装备上斗篷一样:

import { Module } from '[@nestjs](/user/nestjs)/common';
import { JwtModule } from '[@nestjs](/user/nestjs)/jwt';

@Module({
  imports: [
    JwtModule.register({
      secret: '你的超级秘密', // 比如说,蜘蛛侠的“蜘蛛感应”
      signOptions: { expiresIn: '60s' }, // 超级英雄的超时时间
    }),
  ],
})
export class AuthModule {}

最后,创建一个登录服务,让英雄们可以证明自己的身份:

import { Injectable } from '[@nestjs](/user/nestjs)/common';
import { JwtService } from '[@nestjs](/user/nestjs)/jwt';

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

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

现在,每当你的超级英雄想要证明自己时,他们只需调用login方法,就能获得一个神奇的令牌!别忘了,这个令牌就像他们的秘密身份,要小心保管哦!


当然可以。@nestjs/jwt 是一个非常流行的库,用于在 NestJS 应用程序中实现 JWT(JSON Web Token)认证。以下是一个简单的示例,展示如何设置和使用 JWT 认证。

首先,确保你已经安装了必要的依赖包:

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

接下来,配置你的应用程序以使用 JWT。假设你有一个基本的 NestJS 项目结构。

  1. 创建 JWT 模块 (auth/auth.module.ts):
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { JwtStrategy } from './jwt.strategy';

@Module({
  imports: [
    PassportModule,
    JwtModule.register({
      secret: 'your-secret-key', // 请将此替换为安全的密钥
      signOptions: { expiresIn: '60m' },
    }),
  ],
  providers: [AuthService, JwtStrategy],
  controllers: [AuthController],
})
export class AuthModule {}
  1. 创建 JWT 策略 (auth/jwt.strategy.ts):
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', // 请将此替换为与 `AuthModule` 中相同的密钥
    });
  }

  async validate(payload: any) {
    return { userId: payload.sub, username: payload.username };
  }
}
  1. 创建服务和控制器 (auth/auth.service.ts, auth/auth.controller.ts):

auth.service.ts

import { Injectable } from '@nestjs/common';
import * as bcrypt from 'bcryptjs';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  async validateUser(username: string, pass: string): Promise<any> {
    const user = await this.findUser(username); // 这里需要实现具体的用户查找逻辑
    if (user && bcrypt.compareSync(pass, user.password)) {
      const { password, ...result } = user;
      return result;
    }
    return null;
  }

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

auth.controller.ts

import { Controller, Post, Body } from '@nestjs/common';
import { AuthService } from './auth.service';
import { JwtService } from '@nestjs/jwt';

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

  @Post('login')
  async login(@Body() body: { username: string; password: string }) {
    const user = await this.authService.validateUser(body.username, body.password);
    if (user) {
      return this.authService.login(user);
    }
    throw new Error('Invalid credentials');
  }
}

以上就是使用 @nestjs/jwt 的基本步骤。请注意,你需要根据自己的需求调整这些代码,例如处理数据库查询、错误处理等。

使用@nestjs/jwt进行JWT认证主要分为以下几步:

  1. 安装依赖:npm install @nestjs/jwt @nestjs/passport passport passport-jwt

  2. 配置模块,在app.module.ts中导入JwtModule并配置秘钥:

import { JwtModule } from '@nestjs/jwt';
@Module({
  imports: [
    JwtModule.register({
      secret: 'your-secret-key',
      signOptions: { expiresIn: '60s' },
    }),
  ],
})
export class AppModule {}
  1. 创建服务和控制器,使用@Injectable()@Controller()装饰器,通过this.jwtService调用JWT相关方法。

  2. 设置路由守卫或中间件保护路由。

回到顶部