我正在尝试使用passport-google-oauth20库以及@nestjs/jwt创建一个nestjs应用程序 我为 Google 制定了战略
import { Injectable } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { PassportStrategy } from '@nestjs/passport'
import { Profile, Strategy, VerifyCallback } from 'passport-google-oauth20'
@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy) {
constructor(private configService: ConfigService) {
super({
clientID: configService.get('CLIENT_ID'),
clientSecret: configService.get('CLIENT_SECRET'),
callbackURL: configService.get('CALLBACK_URL'),
scope: ['profile', 'email'],
})
}
async validate(
accessToken: string,
refreshToken: string,
profile: Profile,
done: VerifyCallback
) {
const user = {
email: profile.emails[0].value,
name: profile.displayName,
avatar: profile.photos[0].value
}
done(null, user)
}
}
这是我的控制器
import { Controller, Get, Req, Res, UseGuards } from '@nestjs/common'
import { AuthGuard } from '@nestjs/passport'
import { Request, Response } from 'express'
import { AuthService } from './auth.service'
import { IUser } from './types/auth.types'
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Get('google')
@UseGuards(AuthGuard('google'))
googleAuth() {}
@Get('google/redirect')
@UseGuards(AuthGuard('google'))
async googleAuthRedirect(@Req() request: Request, @Res() response: Response) {
const {
tokens: { accessToken, refreshToken },
user
} = await this.authService.googleAuthLogin(request.user as IUser)
}
}
在这里您可以看到端点 /google/redirect,在客户端上,用户单击“使用 Google 登录”按钮,它会重定向到 /google,在我从数据库创建或提供用户的 googleAuthLogin 方法中,我还生成了两个令牌accessToken 和refreshToken。我的目标:将accessToken提供给客户端,以便他可以将其保存在浏览器中,并且我想通过服务器cookie保存refreshToken,然后将其重定向到NextJS客户端上的个人资料页面