【发布时间】:2022-08-04 21:21:07
【问题描述】:
我需要使用 Nest.js 进行身份验证后的处理帮助 在使用 Nest.js 进行身份验证时,我是否通过本地护照的 failureRedirect 选项?
没有 Nest.js
app.post(\'/login\', passport.authenticate(\'local\', {
//Passing options here.
successRedirect: \'/\',
failureRedirect: \'/login\'
}));
我的代码是。 (使用 Nest.js)
本地策略.ts
import { Injectable, UnauthorizedException } from \"@nestjs/common\";
import { PassportStrategy } from \"@nestjs/passport\";
import { Strategy } from \"passport-local\";
import { AuthService } from \"./auth.service\";
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({
//I tried passing the option here. but failed.
})
}
async validate(username: string, password: string): Promise<string | null> {
const user = this.authService.validate(username, password);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
local.guard.ts
import { Injectable } from \"@nestjs/common\";
import { AuthGuard } from \"@nestjs/passport\";
@Injectable
export class LocalAuthGuard extends AuthGuard(\'local\') {}
身份验证控制器.ts
import { Controller, Get, Post, Render, UseGuards } from \"@nestjs/common\";
import { LocalAuthGuard } from \"./local.guard\";
@Controller()
export class AuthController {
@Get(\"/login\")
@Render(\"login\")
getLogin() {}
//Redirect to \'/login\' when authentication failed.
@UseGuards(LocalAuthGuard)
@Post(\"/login\")
postLogin() {}
}
auth.module.ts
import { Module } from \"@nestjs/common\";
import { PassportModule } from \"@nestjs/passport\";
import { AuthController } from \"./auth.controller\";
import { AuthService } from \"./auth.service\";
import { LocalStrategy } from \"./local.strategy\";
import { LocalAuthGuard } from \"./local.guard\";
@Module({
controllers: [AuthController],
imports: [PassportModule],
providers: [AuthService, LocalStrategy, LocalAuthGuard]
})
export class AuthModule {}
我尝试将代码添加到AuthController#postLogin 以在登录失败时重定向,但代码似乎只在成功登录时运行。
如果使用passport-local的failureRedirect选项登录失败,我想再次重定向到登录页面。
标签: node.js nestjs passport.js passport-local nestjs-passport