开门见山
一、第一步
npm i @nestjs/jwt passport-jwt @types/passport-jwt
二、第二步
nest g mo jwtDemo
//新建模块
nest g s jwtDemo
//新建服务
nest g co jwtDemo
三、使用jwt
出于代码规范,我习惯将配置文件都写在config中使用时引入
config.ts
export const jwtKey = {
secret: 'lgldl',
};
jwt-demo.module.ts
import { JwtStrategy } from './jwt.strategy';
import { Module } from '@nestjs/common';
import { JwtDemoService } from './jwt-demo.service';
import { JwtDemoController } from './jwt-demo.controller';
import { JwtModule } from '@nestjs/jwt';
import {jwtKey} from './config'
@Module({
imports: [
JwtModule.register({
//生成token的key
secret:jwtKey.secret,
// signOption可以在JwtModule设定
// 或是在createToken时候设定
signOptions: {
//token的有效时长
expiresIn: '1h',
},
}),
],
providers: [JwtDemoService,JwtStrategy],
controllers: [JwtDemoController]
})
export class JwtDemoModule {}
jwt.strategy.ts //用于验证token
import { Strategy, ExtractJwt } from 'passport-jwt';
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { jwtKey } from './config';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: jwtKey.secret,
});
}
// Passport会自动verify jwt,如果key不正确,或是相关信息
async validate(payload) {
//payload与加密前的json对象一样
//因为已经验证过token了所以在payload中进行验证用户信息是否为空
if(!payload.username || !payload.password) {
return false;
}
let user={ username: payload.username, password: payload.password };
//返回后可在req中得到返回的值
return user;
}
}
jwt-demo.service.ts
import { JwtService } from '@nestjs/jwt';
import { Injectable, UnauthorizedException } from '@nestjs/common';
@Injectable()
export class JwtDemoService {
constructor(
// 注入UsersService,所以需要import UsersModule
// 底下的provider才能被注入
private readonly jwtService: JwtService,
) {}
async createToken(user) {
const payload = {username: user.name, password: user.password};
//在实际项目中一般要进行数据库验证查看用户用户名密码是否正确
//const data = await this.userRepository.findOne({username:user.username, password: user.password})
//if(!data) {
// return {code: 1 , msg:'登录失败', data: ''}
//}
delete user.password;
return {
msg:'登录成功',
data: {
user: user,
//得到token
token: this.jwtService.sign(payload)
},
};
}
}
jwt-demo.control.ts
import { JwtDemoService } from './jwt-demo.service';
import { JwtService } from '@nestjs/jwt';
import { Controller, UseGuards, Get, Post, Req, Body } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Controller('')
export class JwtDemoController {
JwtDemoService: any;
constructor(private readonly jwtDemoService: JwtDemoService){}
//使用jwt验证token的端口
@UseGuards( AuthGuard('jwt'))
@Post('tokenIn')
aPost(@Req() req){
return req.user;
}
@Post('getToken')
getTokenByUserId(
@Body() user: any,
){
return this.jwtDemoService.createToken(user);
}
}
OK
效果如下:
直接访问的话会这样
获取token
在请求中设置token
进行请求