我正在尝试使用 Passportjs 和 NestJS(Fastify 作为底层 HTTP 框架)设置 google oauth2。我无法初始化谷歌身份验证屏幕,每次尝试时都会出现错误。我尝试了几种不同的方法来做到这一点,但是 AuthGuard 似乎存在问题,并且每次在这一步代码都会中断。我在这里共享一个控制器片段,它正在处理用于初始化身份验证屏幕的路由。
这是控制器:
import { Controller, Get, Post, Body, UseGuards, Req, Res } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Controller('auth')
export class AuthController {
@Get('google')
@UseGuards(AuthGuard('google'))
intializeGoogleLogin() {}
}
谷歌战略:
import { Strategy } from 'passport-google-oauth2';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
constructor() {
super({
clientID: <cleintId>,
clientSecret: <clientSecret>,
callbackURL: `/auth/google/callback`,
scope: ['profile', 'email'],
});
}
}
该模块如下所示:
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { GoogleStrategy } from './google.strategy';
@Module({
imports: [],
controllers: [AuthController],
providers: [AuthService, GoogleStrategy],
exports: [],
})
export class AuthModule {}
依赖项
"@nestjs/common": "^7.0.0",
"@nestjs/core": "^7.0.0",
"@nestjs/passport": "^7.0.0",
"@nestjs/platform-fastify": "^7.0.5",
"@nestjs/typeorm": "^7.0.0",
"passport": "^0.4.1",
"passport-google-oauth2": "^0.2.0",
"passport-google-oauth20": "^2.0.0",