【问题标题】:How to pass request object through Nest.js Guards with Nest.js Passport Module and Passport Discord?如何使用 Nestjs Passport Module 和 Passport Discord 通过 Nestjs Guards 传递请求对象?
【发布时间】:2022-11-02 23:23:29
【问题描述】:

我正在使用nest.js 以及它的passport 模块和passport-discord 来处理discord oauth2 身份验证。

但是,我想通过身份验证保护从我的登录路由传递请求对象,以便稍后在我检查一些数据的行中使用,然后在某些情况下需要在请求对象上调用 logOut() 方法。

控制器:

@Get('login')
  @UseGuards(DiscordAuthGuard)
  login() {
    console.log('hello123');
  }

警卫:

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

export class DiscordAuthGuard extends AuthGuard('discord') {
  async canActivate(context: ExecutionContext) {
    const activate = (await super.canActivate(context)) as boolean;
    const request = context.switchToHttp().getRequest();
    await super.logIn(request);
    return activate;
  }
}

不和谐策略:

import { Inject } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Profile, Strategy } from 'passport-discord';
import { IAuthService } from '../interfaces/auth';
export class DiscordStrategy extends PassportStrategy(Strategy) {
  constructor(
    @Inject('AUTH_SERVICE') private readonly authService: IAuthService,
  ) {
    super({
      clientID: 'REDACTED',
      clientSecret: 'REDACTED',
      callbackURL: 'http://localhost:4000/api/auth/redirect',
      scope: ['identify'],
    });
  }

  async validate(accessToken: string, refreshToken: string, profile: Profile) {
    console.log('DiscordStrategy Validate Method');
    console.log(profile);
// I WANT TO BE ABLE TO GET THE REQUEST OBJECT TO HERE, SO THAT I CAN PASS IT INTO MY AUTH SERVICE
    return this.authService.validateUser({ discordId: profile.id });
  }
}

知道我将如何实现这一目标吗?

【问题讨论】:

    标签: node.js nestjs passport.js nestjs-passport


    【解决方案1】:

    尝试在构造函数中将 passReqToCallback 参数传递给 super:

    constructor(
        @Inject('AUTH_SERVICE') private readonly authService: IAuthService,
      ) {
        super({
          clientID: 'REDACTED',
          clientSecret: 'REDACTED',
          callbackURL: 'http://localhost:4000/api/auth/redirect',
          scope: ['identify'],
          passReqToCallback: true,
        });
      }
    

    并修改验证功能以具有签名

    async validate(req: Request, accessToken: string, refreshToken: string, profile: Profile)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-01
      • 2022-07-02
      • 2020-07-18
      • 2020-03-24
      • 2019-04-15
      • 2019-06-29
      • 2021-05-28
      • 2020-06-09
      相关资源
      最近更新 更多