完成jwt鉴权

This commit is contained in:
2025-05-07 14:34:49 +08:00
parent d2744689b2
commit 1246613fb1
9 changed files with 139 additions and 17 deletions

View File

@@ -1,4 +1,4 @@
import { BadRequestException, Body, Controller, Post } from '@nestjs/common';
import { BadRequestException, Body, Controller, Get, Post, Request } from '@nestjs/common';
import { LoginDto } from './dto/login.dto';
import { AuthService } from './auth.service';

View File

@@ -1,24 +1,40 @@
import { Module } from '@nestjs/common';
import { forwardRef, Module } from '@nestjs/common';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { UserModule } from 'src/user/user.module';
import { JwtModule } from '@nestjs/jwt';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserSession } from 'src/user/entities/user-session.entity';
import { UserSessionService } from 'src/user/services/user-session.service';
import { PassportModule } from '@nestjs/passport';
import { JwtStrategy } from './strategies/jwt.strategy';
import { ConfigModule, ConfigService } from '@nestjs/config';
@Module({
imports: [
UserModule,
ConfigModule,
forwardRef(() => UserModule),
TypeOrmModule.forFeature([UserSession]),
JwtModule.register({
secret: process.env.JWT_SECRET || 'tone-page',
signOptions: {
expiresIn: process.env.EXPIRES_IN || '1d',
}
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
secret: configService.get<string>('JWT_SECRET', 'tone-page'),
signOptions: {
expiresIn: configService.get<string>('JWT_EXPIRES_IN', '1d'),
},
})
})
],
controllers: [AuthController],
providers: [AuthService, UserSessionService],
providers: [
AuthService,
JwtStrategy,
],
exports: [
PassportModule,
JwtStrategy,
AuthService,
]
})
export class AuthModule { }

View File

@@ -0,0 +1,33 @@
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy } from "passport-jwt";
import { UserSessionService } from "src/user/services/user-session.service";
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor(
private readonly userSessionService: UserSessionService,
private readonly configService: ConfigService,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: configService.get<string>('JWT_SECRET', 'tone-page'),
})
}
async validate(payload: any) {
const { userId, sessionId } = payload ?? {};
const isValidSession = await this.userSessionService.isSessionValid(userId, sessionId);
if (!isValidSession) {
throw new UnauthorizedException('登录凭证已过期,请重新登录');
}
return {
userId,
sessionId,
}
}
}