Token验证
sonder 默认

Token验证

  • 安装
1
yarn add @nestjs/jwt passport-jwt @types/passport-jwt
  • 建立一个auth.module.ts模块来管理权限
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { JwtStrategy } from './jwt.strategy';
import { JwtModule} from '@nestjs/jwt';
import { AuthController } from './auth.controller';
import { PassportModule } from '@nestjs/passport';
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt',session:false }),
JwtModule.register({
// 这里的secret要统一
secret: 'jwtConstants.secret',
// 过期时间2小时
signOptions: { expiresIn: '2h' },
})
],
providers: [AuthService,JwtStrategy],
ontrollers:[AuthController],
// 暴露出去
exports: [AuthService],
})
export class AuthModule {}
  • 验证文件jwt.strategy.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { ExtractJwt, Strategy } from 'passport-jwt';
import {AuthService } from './auth.service';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'jwtConstants.secret',
});
}
/**
* 验证JWT令牌信息
* @param req 请求上下文
* @param devId 设备唯一ID
* @param sign 提交数据签名
* @param verified 验证回调方法(不需要主动调用该方法)
*/
async validate(payload:any) {
const user = await this.authService.validateUser(payload);
if (!user) throw new UnauthorizedException();
return user;
}
}
  • auth.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

import { Injectable } from '@nestjs/common';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
payload: any;
constructor(
// 底下的provider才能被注入
private readonly jwtService : JwtService ,
){}
async createToken(username: string, password: string) {
// const expiration = 600 * 1000;
this.payload = { username: username, password: password};
return this.jwtService.sign(this.payload)
}
// 检验token合法性
async validateUser(payloads:any) {
if(payloads.username === 'cjq' && payloads.password =='123'){
return payloads
}else{
return null
}
}
}
  • 最后在控制器里提供登陆接口,如果登陆成功,则请求获取token。

  • 每定义一个接口时这样使用

1
2
3
4
5
6
7
8
9
10
@Get('test')
// 如此使用
@UseGuards(AuthGuard('jwt'))
test() {
const obj ={
status:200,
data :{}
}
return obj;
}
  • 本文标题:Token验证
  • 本文作者:sonder
  • 创建时间:2020-05-20 14:48:55
  • 本文链接:https://sonderss.github.io/2020/05/20/Token验证/
 评论