Nodejs Nestjs插件passport-google-oauth20实现Google OAuth2.0认证的使用
Nodejs Nestjs插件passport-google-oauth20实现Google OAuth2.0认证的使用
在NestJS中使用passport-google-oauth20
插件来实现Google OAuth2.0认证是一个常见的需求。下面将详细介绍如何配置和使用这个插件。
1. 安装必要的依赖
首先,你需要安装@nestjs/passport
, passport
, passport-google-oauth20
以及@nestjs/jwt
(如果你需要JWT认证):
npm install @nestjs/passport passport passport-google-oauth20 @nestjs/jwt
2. 创建策略
创建一个GoogleOAuthStrategy类来处理Google OAuth2.0登录过程:
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, VerifyCallback } from 'passport-google-oauth20';
@Injectable()
export class GoogleOAuthStrategy extends PassportStrategy(Strategy, 'google') {
constructor() {
super({
clientID: 'YOUR_GOOGLE_CLIENT_ID',
clientSecret: 'YOUR_GOOGLE_CLIENT_SECRET',
callbackURL: 'http://localhost:3000/auth/google/callback',
scope: ['profile', 'email'],
});
}
async validate(
accessToken: string,
refreshToken: string,
profile: any,
done: VerifyCallback,
): Promise<any> {
const { name, emails, photos } = profile;
const user = {
email: emails[0].value,
firstName: name.givenName,
lastName: name.familyName,
picture: photos[0].value,
accessToken,
};
done(null, user);
}
}
3. 配置模块
在你的模块文件中配置Passport和GoogleOAuthStrategy:
import { Module } from '@nestjs/common';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { LocalStrategy } from './local.strategy';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import { GoogleOAuthStrategy } from './google-oauth.strategy';
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'google' }),
JwtModule.register({
secret: 'your_jwt_secret',
signOptions: { expiresIn: '60m' },
}),
],
controllers: [AuthController],
providers: [AuthService, LocalStrategy, GoogleOAuthStrategy],
})
export class AuthModule {}
4. 创建控制器
创建一个控制器来处理Google OAuth2.0登录请求:
import { Controller, Get, Req, Res } from '@nestjs/common';
import { Request, Response } from 'express';
import { AuthService } from './auth.service';
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Get('google')
async googleAuth(@Req() req: Request, @Res() res: Response) {
res.redirect(this.authService.googleAuth());
}
@Get('google/callback')
async googleAuthRedirect(@Req() req: Request, @Res() res: Response) {
try {
const user = await this.authService.googleLogin(req);
res.send(user);
} catch (error) {
res.status(500).send(error.message);
}
}
}
5. 配置服务
最后,在你的AuthService中添加处理逻辑:
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-google-oauth20';
@Injectable()
export class AuthService {
googleAuth() {
return `https://accounts.google.com/o/oauth2/auth?client_id=${process.env.GOOGLE_CLIENT_ID}&redirect_uri=${process.env.GOOGLE_REDIRECT_URL}&response_type=code&scope=email%20profile`;
}
async googleLogin(req: Request) {
if (!req.user) {
throw new Error('User not authenticated');
}
return req.user;
}
}
确保在环境变量中设置GOOGLE_CLIENT_ID
, GOOGLE_CLIENT_SECRET
, 和 GOOGLE_REDIRECT_URL
。
以上就是使用passport-google-oauth20
插件在NestJS中实现Google OAuth2.0认证的基本步骤。
当然,要使用passport-google-oauth20
插件在NestJS中实现Google OAuth2.0认证,你可以按照以下步骤来操作:
-
安装依赖: 首先,你需要安装必要的库。打开你的项目终端,运行以下命令:
npm install [@nestjs](/user/nestjs)/passport passport passport-google-oauth20 passport-strategy
-
配置策略: 创建一个GoogleOAuthStrategy类,用于处理Google OAuth2.0登录逻辑。
-
设置路由: 在你的模块中配置Passport中间件,并设置相应的路由来启动和完成OAuth流程。
-
环境变量: 确保在你的
.env
文件中设置了Google客户端ID和客户端密钥。 -
测试: 启动应用,访问你的登录路由,你应该会被重定向到Google的登录页面。成功登录后,用户信息将被保存或直接返回给前端。
这只是一个大致的指南,具体实现细节可能会根据你的项目需求有所不同。希望这能帮到你!如果需要更详细的代码示例,可以继续提问哦!
要使用passport-google-oauth20
插件在NestJS中实现Google OAuth2.0认证,首先需要安装必要的依赖:
npm install @nestjs/passport passport passport-google-oauth20 passport-strategy
npm install --save @nestjs/throttler
接着,在你的模块中配置Passport模块,并设置GoogleOAuthStrategy。你需要从Google获取客户端ID和秘密,然后将其传递给策略。
最后,在路由中应用此策略,用户将被重定向到Google进行身份验证,之后会返回到你的应用并完成登录流程。详细步骤可以参考官方文档或相关教程。