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新版教程(有挂辅助)-哔哩哔哩您好:杭州...
2024教程"云麻圈... 2024教程"云麻圈修改器"开挂(透视)辅助平台(果然确实有挂)-哔哩哔哩;最新版2026是一款经典...
透视科技!皮皮辅助软件,凑一桌... 皮皮辅助软件 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理由: 1、软...
1.9分钟了解"指尖... 1.9分钟了解"指尖四川刷无限钻石"开挂(透视)辅助插件(一直真的有挂)-哔哩哔哩;1、不需要AI权...
指导大家!斗城麻将微信有没有挂... 指导大家!斗城麻将微信有没有挂,广西友乐辅助app,微扑克教程(有挂教学)-哔哩哔哩斗城麻将微信有没...
记者揭秘"皮皮山西挖... 记者揭秘"皮皮山西挖坑辅助"开挂(透视)辅助平台(一直确实是有挂)-哔哩哔哩;皮皮山西挖坑辅助最新软...
最新技巧!潮汕汇木虱辅助下载,... >>您好:潮汕汇木虱辅助下载确实是有挂的,很多玩家在这款潮汕汇木虱辅助下载游戏中打牌都会发现很多用户...
查到实测辅助"微信江... 查到实测辅助"微信江苏小程序游戏破解器下载"开挂(透视)辅助平台(原来确实有挂的)-哔哩哔哩;微信江...
热点推荐!微乐脚本,浙江宝宝游... 热点推荐!微乐脚本,浙江宝宝游戏辅助软件,教你攻略(有挂技巧)-哔哩哔哩 【无需打开直接搜索加薇13...