身份认证(JWT)
原创2026/3/5大约 2 分钟
安装
npm install --save @nestjs/jwt配置
import { Module } from '@nestjs/common'
import { AppController } from './app.controller'
import { AppService } from './app.service'
import { TypeOrmModule } from '@nestjs/typeorm'
import { App } from './app.entity'
import { JwtModule } from '@nestjs/jwt'
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql',
host: 'wwlj-yunfuwu.mysql.huhehaote.rds.aliyuncs.com',
port: 3306,
username: 'j******9',
password: 'A**********0',
database: 'jiamei',
retryDelay: 500,
retryAttempts: 10,
autoLoadEntities: true,
synchronize: true,
}),
TypeOrmModule.forFeature([App]),
JwtModule.register({
global: true,
secret: 'ahckcsksvcs',
signOptions: { expiresIn: '120s' },
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}模型
import { Entity, Column, PrimaryGeneratedColumn, BeforeInsert } from 'typeorm'
import * as bcrypt from 'bcrypt'
@Entity()
export class App {
@PrimaryGeneratedColumn()
id: number
@Column()
userName: string
@Column()
passWord: string
@BeforeInsert()
async hashPassword() {
this.passWord = await bcrypt.hash(this.passWord, 10)
}
@Column({ default: true })
isActive: boolean
@Column({ default: 'user' })
role: string
}生成Token
import { Injectable } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import { InjectRepository } from '@nestjs/typeorm'
import { App } from './app.entity'
import { Repository } from 'typeorm'
import * as bcrypt from 'bcrypt'
@Injectable()
export class AppService {
constructor(
@InjectRepository(App)
private readonly appRepository: Repository<App>,
private readonly jwtService: JwtService,
) {}
async login() {
const username = 'admin'
const password = '123456'
const user = await this.appRepository.findOne({
where: {
userName: username,
},
})
if (!user) {
return '用户不存在'
}
if (user?.passWord && !(await bcrypt.compare(password, user.passWord))) {
return '密码错误'
}
return {
code: 200,
msg: '登录成功',
token: await this.jwtService.signAsync({ ...user }),
}
}
async mustLogin() {}
}新建身份守卫
nest g gu ./guard/authenticationimport { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import { Request } from 'express'
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private jwtService: JwtService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest()
const token = this.extractTokenFromHeader(request)
if (!token) {
throw new UnauthorizedException()
}
try {
const payload = await this.jwtService.verifyAsync(token, {
secret: 'ahckcsksvcs',
})
request['user'] = payload
} catch {
throw new UnauthorizedException()
}
return true
}
private extractTokenFromHeader(request: Request): string | undefined {
const [type, token] = request.headers.authorization?.split(' ') ?? []
return type === 'Bearer' ? token : undefined
}
}使用
app.controller.ts
import { Controller, Get, Req, UseGuards } from '@nestjs/common'
import { AppService } from './app.service'
import { AuthGuard } from 'src/guard/authentication/authentication.guard'
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get('login')
login() {
return this.appService.login()
}
@UseGuards(AuthGuard)
@Get('mustLogin')
mustLogin(@Req() req: any) {
return this.appService.mustLogin(req)
}
}app.service.ts
import { Injectable } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import { InjectRepository } from '@nestjs/typeorm'
import { App } from './app.entity'
import { Repository } from 'typeorm'
import * as bcrypt from 'bcrypt'
@Injectable()
export class AppService {
constructor(
@InjectRepository(App)
private readonly appRepository: Repository<App>,
private readonly jwtService: JwtService,
) {}
async login() {
const username = 'admin'
const password = '123456'
const user = await this.appRepository.findOne({
where: {
userName: username,
},
})
if (!user) {
return '用户不存在'
}
if (user?.passWord && !(await bcrypt.compare(password, user.passWord))) {
return '密码错误'
}
return {
code: 200,
msg: '登录成功',
token: await this.jwtService.signAsync({ ...user }),
}
}
async mustLogin(req: any) {
return req.user
}
}至此,本章节的学习就到此结束了,如有疑惑,可对接技术客服进行相关咨询。