1.@nestjs/jwt
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Authing, AuthUser } from '../../decorators/common.decorator';
export type User = any;
@Injectable()
export class AuthService {
private readonly users: User[];
constructor(private readonly jwtService: JwtService) {
this.users = [
{
userId: 1,
username: 'john',
password: 'changeme',
},
{
userId: 2,
username: 'chris',
password: 'secret',
},
{
userId: 3,
username: 'maria',
password: 'guess',
},
];
}
async validateUser(username: string, pass: string): Promise<any> {
const user = await this.findOne(username);
if (user && user.password === pass) {
const { password, ...result } = user;
return result;
}
return null;
}
async findOne(username: string): Promise<User | undefined> {
return this.users.find(user => user.username === username);
}
async login(user: any) {
const payload = { username: user.username, sub: user.userId };
const accessToken = this.jwtService.sign(payload);
console.log(accessToken, 'accessToken');
return {
accessToken: accessToken,
};
}
async authLogin(@Authing() user: any) {
const payload = { username: user.username, sub: user.userId };
try {
const result = await user.login(payload);
return result;
} catch (err) {
console.log(err);
}
// return {
// access_token: this.jwtService.sign(payload),
// };
}
}
2.
import { JwtService } from '@nestjs/jwt';
// JWT验证 - Step 3: 处理 jwt 签证
async certificate(user: any) {
const payload = { username: user.username, sub: user.userId, realName: user.realName, role: user.role };
console.log('JWT验证 - Step 3: 处理 jwt 签证');
try {
const token = this.jwtService.sign(payload);
return {
code: 200,
data: {
token,
},
msg: `登录成功`,
};
} catch (error) {
return {
code: 600,
msg: `账号或密码错误`,
};
}
}
}
3.
const token = await this._authService.signPayload(payload);
import { forwardRef, Inject, Injectable } from '@nestjs/common';
import { sign, SignOptions } from 'jsonwebtoken';
import { User } from '../modules/user/models/user.model';
import { UserService } from '../modules/user/user.service';
import { JwtPayload } from './jwt-payload.model';
import { ConfigService } from '../../config/config.service';
const config = new ConfigService(`env/${process.env.NODE_ENV}.env`);
@Injectable()
export class AuthService {
private readonly jwtOptions: SignOptions;
private readonly jwtKey: string;
constructor(
@Inject(forwardRef(() => UserService))
readonly _userService: UserService,
) {
// secretOrPublicKey/jwtKey是一个字符串或缓冲区,
// 其中包含HMAC算法的机密,或包含RSA和ECDSA的PEM编码的公钥
// jwtKey不能告诉其他人
this.jwtOptions = { expiresIn: '12h' };
this.jwtKey = config.jwtKey;
}
async signPayload(payload: JwtPayload): Promise<string> {
console.log(payload, this.jwtKey, this.jwtOptions);
return sign(payload, this.jwtKey, this.jwtOptions);
}
async validateUser(validatePayload: JwtPayload): Promise<User> {
return this._userService.findOne({ username: validatePayload.username.toLowerCase() });
}
}
两种实现方式@nestjs/jwt和AuthService自定义