1.@nestjs/jwt

    1. import { Injectable } from '@nestjs/common';
    2. import { JwtService } from '@nestjs/jwt';
    3. import { Authing, AuthUser } from '../../decorators/common.decorator';
    4. export type User = any;
    5. @Injectable()
    6. export class AuthService {
    7. private readonly users: User[];
    8. constructor(private readonly jwtService: JwtService) {
    9. this.users = [
    10. {
    11. userId: 1,
    12. username: 'john',
    13. password: 'changeme',
    14. },
    15. {
    16. userId: 2,
    17. username: 'chris',
    18. password: 'secret',
    19. },
    20. {
    21. userId: 3,
    22. username: 'maria',
    23. password: 'guess',
    24. },
    25. ];
    26. }
    27. async validateUser(username: string, pass: string): Promise<any> {
    28. const user = await this.findOne(username);
    29. if (user && user.password === pass) {
    30. const { password, ...result } = user;
    31. return result;
    32. }
    33. return null;
    34. }
    35. async findOne(username: string): Promise<User | undefined> {
    36. return this.users.find(user => user.username === username);
    37. }
    38. async login(user: any) {
    39. const payload = { username: user.username, sub: user.userId };
    40. const accessToken = this.jwtService.sign(payload);
    41. console.log(accessToken, 'accessToken');
    42. return {
    43. accessToken: accessToken,
    44. };
    45. }
    46. async authLogin(@Authing() user: any) {
    47. const payload = { username: user.username, sub: user.userId };
    48. try {
    49. const result = await user.login(payload);
    50. return result;
    51. } catch (err) {
    52. console.log(err);
    53. }
    54. // return {
    55. // access_token: this.jwtService.sign(payload),
    56. // };
    57. }
    58. }

    2.

    1. import { JwtService } from '@nestjs/jwt';
    2. // JWT验证 - Step 3: 处理 jwt 签证
    3. async certificate(user: any) {
    4. const payload = { username: user.username, sub: user.userId, realName: user.realName, role: user.role };
    5. console.log('JWT验证 - Step 3: 处理 jwt 签证');
    6. try {
    7. const token = this.jwtService.sign(payload);
    8. return {
    9. code: 200,
    10. data: {
    11. token,
    12. },
    13. msg: `登录成功`,
    14. };
    15. } catch (error) {
    16. return {
    17. code: 600,
    18. msg: `账号或密码错误`,
    19. };
    20. }
    21. }
    22. }

    3.

    1. const token = await this._authService.signPayload(payload);
    1. import { forwardRef, Inject, Injectable } from '@nestjs/common';
    2. import { sign, SignOptions } from 'jsonwebtoken';
    3. import { User } from '../modules/user/models/user.model';
    4. import { UserService } from '../modules/user/user.service';
    5. import { JwtPayload } from './jwt-payload.model';
    6. import { ConfigService } from '../../config/config.service';
    7. const config = new ConfigService(`env/${process.env.NODE_ENV}.env`);
    8. @Injectable()
    9. export class AuthService {
    10. private readonly jwtOptions: SignOptions;
    11. private readonly jwtKey: string;
    12. constructor(
    13. @Inject(forwardRef(() => UserService))
    14. readonly _userService: UserService,
    15. ) {
    16. // secretOrPublicKey/jwtKey是一个字符串或缓冲区,
    17. // 其中包含HMAC算法的机密,或包含RSAECDSAPEM编码的公钥
    18. // jwtKey不能告诉其他人
    19. this.jwtOptions = { expiresIn: '12h' };
    20. this.jwtKey = config.jwtKey;
    21. }
    22. async signPayload(payload: JwtPayload): Promise<string> {
    23. console.log(payload, this.jwtKey, this.jwtOptions);
    24. return sign(payload, this.jwtKey, this.jwtOptions);
    25. }
    26. async validateUser(validatePayload: JwtPayload): Promise<User> {
    27. return this._userService.findOne({ username: validatePayload.username.toLowerCase() });
    28. }
    29. }

    两种实现方式@nestjs/jwt和AuthService自定义