nestjs学习笔记
1、使用 @nestjs/jwt做登录验证
- //安装 @nestjs/jwt
yarn add @nestjs/jwt
创建local.strategy.ts文件
import { PassportStrategy } from '@nestjs/passport';
import { IStrategyOptions, Strategy } from 'passport-local';
import { user } from '../entity/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { UserService } from '../user.service'
import { BadRequestException, Injectable } from '@nestjs/common';
@Injectable()
export class LocalStorage extends PassportStrategy(Strategy) {
constructor(
private readonly userService: UserService,
) {
super({
usernameField: 'username',
passwordField: 'password',
} as IStrategyOptions);
}
async validate(username: string, password: string): Promise<any> {
const user = await this.userService.login(username, password)
return user;
}
}
export const jwtContants = {
secret: 'json_web_token_secret_key',
};
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { jwtContants } from './jwt.contants';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { user } from './entity/user.entity';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromHeader('token'),
secretOrKey: jwtContants.secret,
});
}
async validate(payload: any) {
console.log('payload', payload);
return { username: payload.username, id: payload.sub };
}
}
@UseGuards(AuthGuard('local'))