JwtStrategy.ts 790 B

123456789101112131415161718192021222324
  1. import { PrismaService } from './../prisma/prisma.service'
  2. import { ConfigService } from '@nestjs/config'
  3. import { ExtractJwt, Strategy } from 'passport-jwt'
  4. import { PassportStrategy } from '@nestjs/passport'
  5. import { Injectable } from '@nestjs/common'
  6. @Injectable()
  7. export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
  8. constructor(configService: ConfigService, private prisma: PrismaService) {
  9. super({
  10. //解析用户提交的header中的Bearer Token数据
  11. jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  12. //加密码的 secret
  13. secretOrKey: configService.get('TOKEN_SECRET'),
  14. })
  15. }
  16. //验证通过后获取用户资料
  17. async validate({ sub: id }) {
  18. return this.prisma.user.findUnique({
  19. where: { id },
  20. })
  21. }
  22. }