AuthGuard('local')和PassportStrategy(Strategy,'local')有什么区别?
创始人
2024-09-22 15:00:19
0

两者都是用于身份验证的工具,但是Authguard是一个可重用的守卫,可以用于保护路由,确保只有已经经过身份验证的用户才可以访问该路由。而PassportStrategy是一个认证策略,用于设置验证逻辑和认证后的回调。

我们可以通过以下代码示例来进一步说明:

AuthGuard例子:

import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {}

在路由中使用LocalAuthGuard:

import { Controller, Request, Post, UseGuards } from '@nestjs/common';
import { LocalAuthGuard } from './local-auth.guard';

@Controller('auth')
export class AuthController {
  @UseGuards(LocalAuthGuard)
  @Post('login')
  async login(@Request() req) {
    return req.user;
  }
}

PassportStrategy例子:

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();
  }

  async validate(username: string, password: string): Promise {
    const user = await this.authService.validateUser(username, password);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}

在AuthModule中应用LocalStrategy:

import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { LocalStrategy } from './local.strategy';

@Module({
  providers: [AuthService, LocalStrategy],
  controllers: [AuthController],
})
export class AuthModule {}

在AuthController中使用Passport和LocalStrategy:

import { Controller, Request, Post, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Controller('auth')
export class AuthController {
  @UseGuards(AuthGuard('local'))
  @Post('login')
  async login(@Request() req) {
    return req.user;
  }
}

总结:

AuthGuard和PassportStrategy都是用于身份验证的工具,但是它们的使用场景不同。AuthGuard可以用于守卫路由,确保只有已经经过身份验证的用户才可以访问该路由;而PassportStrategy用于设置验证逻辑和认证后的回调,在AuthModule中应用LocalStrategy,在AuthController中使用AuthGuard以确保路由安全。

相关内容

热门资讯

2026版总结!hhpoker... 2026版总结!hhpoker脚本下载,德普之星辅助工具如何打开,切实真的是有挂(有挂教程)1、该软...
推出新举措!悦扑克脚本,德普之... 推出新举措!悦扑克脚本,德普之星透视辅助,果然确实有挂(有挂秘诀)亲,关键说明,德普之星透视辅助透视...
今天上午!wepoker辅助器... 今天上午!wepoker辅助器软件下载,德普之星私人局透视,都是是有挂(有挂实锤)1)德普之星私人局...
攻略辅助挂!wpk有辅助器吗,... 攻略辅助挂!wpk有辅助器吗,德普之星透视辅助软件是真的吗,本来存在有挂(新版有挂)亲,关键说明,德...
据目击者称!xpoker辅助助... 据目击者称!xpoker辅助助手,德普之星透视辅助软件下载,一直真的有挂(有挂详情)进入游戏-大厅左...
刚刚!智星菠萝透视,智星德州辅... 刚刚!智星菠萝透视,智星德州辅助译码插件靠谱吗,好像是有挂(的确有挂)进入游戏-大厅左侧-新手福利-...
教学辅助挂!wepokerh5... 教学辅助挂!wepokerh5破解,德普之星app安卓版破解版,都是确实有挂(有挂详情)1、许多玩家...
此事引发网友热议!pokemm... 此事引发网友热议!pokemmo手机版脚本,德普之星透视辅助插件,总是确实有挂(有挂方针)1、完成德...
针对!wepoker怎么挂飞机... 针对!wepoker怎么挂飞机,德扑之星私人局透视,好像是有挂(有挂教学)1、下载好德扑之星私人局透...
据权威媒体报道!aapoker... 据权威媒体报道!aapoker发牌逻辑,德普之星有透视辅助吗,总是真的有挂(详细教程)1、德普之星有...