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认证的基本步骤。


3 回复

当然,要使用passport-google-oauth20插件在NestJS中实现Google OAuth2.0认证,你可以按照以下步骤来操作:

  1. 安装依赖: 首先,你需要安装必要的库。打开你的项目终端,运行以下命令:

    npm install [@nestjs](/user/nestjs)/passport passport passport-google-oauth20 passport-strategy
    
  2. 配置策略: 创建一个GoogleOAuthStrategy类,用于处理Google OAuth2.0登录逻辑。

  3. 设置路由: 在你的模块中配置Passport中间件,并设置相应的路由来启动和完成OAuth流程。

  4. 环境变量: 确保在你的.env文件中设置了Google客户端ID和客户端密钥。

  5. 测试: 启动应用,访问你的登录路由,你应该会被重定向到Google的登录页面。成功登录后,用户信息将被保存或直接返回给前端。

这只是一个大致的指南,具体实现细节可能会根据你的项目需求有所不同。希望这能帮到你!如果需要更详细的代码示例,可以继续提问哦!


使用passport-google-oauth20插件来实现Google OAuth2.0认证在NestJS中是非常常见的。下面是一个简单的教程,展示如何配置和使用这个插件。

1. 安装依赖

首先,你需要安装必要的包:

npm install @nestjs/passport passport passport-google-oauth20 passport-local @nestjs/jwt @nestjs/axios

2. 配置Passport策略

在你的NestJS项目中创建一个服务文件(例如auth.service.ts),用来处理Google OAuth策略:

import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, VerifyCallback } from 'passport-google-oauth20';

@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
    constructor() {
        super({
            clientID: process.env.GOOGLE_CLIENT_ID,
            clientSecret: process.env.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. 设置路由

接下来,在你的控制器文件(如auth.controller.ts)中设置OAuth路由:

import { Controller, Get, Req, Res } from '@nestjs/common';
import { Request, Response } from 'express';
import { AuthGuard } from '@nestjs/passport';

@Controller('auth')
export class AuthController {
    @Get('google')
    @UseGuards(AuthGuard('google'))
    googleAuth(@Req() req) {
        // This is just a trigger for the authentication process
    }

    @Get('google/callback')
    @UseGuards(AuthGuard('google'))
    googleAuthRedirect(@Req() req, @Res() res) {
        if (req.user) {
            return res.redirect(`http://localhost:4200?token=${req.user.accessToken}`);
        }
    }
}

4. 环境变量

确保在你的环境变量文件(.env)中添加Google OAuth客户端ID和密钥:

GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret

5. 启动应用

最后,启动你的NestJS应用:

npm run start

现在你可以通过访问http://localhost:3000/auth/google开始OAuth流程了。当用户成功登录后,他们将被重定向回你的前端应用,并附带一个访问令牌。

以上步骤提供了一个基本的框架,你可以根据需要进行调整和扩展。

要使用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进行身份验证,之后会返回到你的应用并完成登录流程。详细步骤可以参考官方文档或相关教程。

回到顶部