Nestjs教程集成OAuth认证

我在学习Nestjs集成OAuth认证时遇到了一些问题:

  1. 如何在Nestjs中配置OAuth2.0认证?官方文档看不太明白,有没有更详细的步骤说明?
  2. 使用哪个Nestjs OAuth库比较合适?Passport.js的适配方案是最佳选择吗?
  3. 集成过程中出现"Invalid client credentials"错误该如何排查?
  4. 如何实现不同OAuth提供商(Google/Github等)的多平台登录?需要为每个平台单独写策略吗?
  5. 获取用户信息后,如何与本地用户系统关联并生成JWT?

希望有经验的前辈能分享下完整的集成流程和常见问题的解决方案。


3 回复

要在NestJS中集成OAuth认证,你可以使用[@nestjs](/user/nestjs)/passport和相应的OAuth策略(如Google、GitHub等)。以下是基本步骤:

  1. 安装依赖

    npm install [@nestjs](/user/nestjs)/passport passport passport-google-oauth20
    
  2. 配置Passport
    创建一个模块用于处理认证逻辑,例如AuthModule

  3. 创建Google OAuth策略
    strategies目录下创建google.strategy.ts

    import { Strategy } from 'passport-google-oauth20';
    import { PassportStrategy } from '[@nestjs](/user/nestjs)/passport';
    import { Injectable, UnauthorizedException } from '[@nestjs](/user/nestjs)/common';
    
    [@Injectable](/user/Injectable)()
    export class GoogleStrategy extends PassportStrategy(Strategy) {
        constructor() {
            super({
                clientID: 'your-client-id',
                clientSecret: 'your-client-secret',
                callbackURL: 'http://localhost:3000/auth/google/callback',
                scope: ['profile', 'email'],
            });
        }
    
        async validate(accessToken: string, refreshToken: string, profile, done: Function) {
            const { id, emails, name } = profile;
            const user = { id, email: emails[0].value, name: `${name.givenName} ${name.familyName}` };
            done(null, user);
        }
    }
    
  4. 注册策略
    AuthModule中注册策略:

    [@Module](/user/Module)({
        imports: [
            PassportModule.register({ defaultStrategy: 'google' }),
            GoogleStrategy,
        ],
        providers: [],
    })
    export class AuthModule {}
    
  5. 创建路由
    创建控制器并设置登录和回调路由:

    [@Controller](/user/Controller)('auth')
    export class AuthController {
        @Get('google')
        async login() {
            return this.authService.loginWithGoogle();
        }
    
        @Get('google/callback')
        async callback(@Request() req) {
            if (!req.user) throw new UnauthorizedException();
            return req.user;
        }
    }
    
  6. 启动服务器
    确保OAuth应用的回调地址与callbackURL一致。运行项目后,访问/auth/google即可跳转到OAuth授权页面。

通过这些步骤,你就可以在NestJS中实现Google OAuth认证了。其他OAuth提供方类似,只需调整策略即可。


要实现NestJS的OAuth认证,首先需安装@nestjs/passportpassport-oauth2等依赖:

npm install @nestjs/passport passport passport-oauth2 --save
  1. 配置OAuth策略:创建一个OAuthStrategy类,继承自PassportStrategy,并在构造函数中注入OAuth相关配置。

  2. 注册策略:在模块中使用@UseGuards(AuthGuard('oauth'))装饰器保护路由。通过passport.use()注册OAuth策略。

  3. 回调处理:设置OAuth回调路由,处理登录后的用户信息。

  4. 序列化/反序列化用户:使用@Injectable({ scope: Scope.TRANSIENT })的Serializer类来管理用户会话。

  5. 环境变量:设置客户端ID、客户端密钥和回调URL等OAuth参数到.env文件。

例如,Google OAuth配置:

@Injectable()
export class GoogleOAuthStrategy extends PassportStrategy(Strategy, 'google') {
  constructor() {
    super({
      clientID: 'your-client-id',
      clientSecret: 'your-client-secret',
      callbackURL: 'http://localhost:3000/auth/google/callback',
      scope: ['profile', 'email'],
    });
  }

  async validate(accessToken: string, refreshToken: string, profile: any) {
    // 处理OAuth返回的用户信息
    return { id: profile.id, email: profile.emails[0].value };
  }
}

最后,在模块中导入PassportModule并注册策略。这样就完成了基本的OAuth认证集成。

NestJS 集成 OAuth 认证教程

OAuth 是一种流行的授权协议,允许用户在不共享密码的情况下授权第三方应用访问其资源。下面是 NestJS 集成 OAuth 认证的基本步骤:

1. 安装必要依赖

npm install passport passport-oauth2
npm install @nestjs/passport passport-google-oauth20 --save

2. 创建 OAuth 策略

// src/auth/google.strategy.ts
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } 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: process.env.GOOGLE_CALLBACK_URL,
      scope: ['email', 'profile'],
    });
  }

  async validate(accessToken: string, refreshToken: string, profile: any) {
    const { name, emails } = profile;
    const user = {
      email: emails[0].value,
      firstName: name.givenName,
      lastName: name.familyName,
      accessToken,
    };
    return user;
  }
}

3. 创建认证模块

// src/auth/auth.module.ts
import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { GoogleStrategy } from './google.strategy';

@Module({
  imports: [PassportModule.register({ defaultStrategy: 'google' })],
  providers: [GoogleStrategy],
})
export class AuthModule {}

4. 创建控制器处理回调

// src/auth/auth.controller.ts
import { Controller, Get, Req, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Controller('auth')
export class AuthController {
  @Get('google')
  @UseGuards(AuthGuard('google'))
  async googleAuth() {
    // 启动Google OAuth流程
  }

  @Get('google/callback')
  @UseGuards(AuthGuard('google'))
  googleAuthRedirect(@Req() req) {
    return req.user; // 返回用户信息
  }
}

5. 配置环境变量 (.env)

GOOGLE_CLIENT_ID=your_client_id
GOOGLE_CLIENT_SECRET=your_client_secret
GOOGLE_CALLBACK_URL=http://localhost:3000/auth/google/callback

6. 注册模块

// src/app.module.ts
import { Module } from '@nestjs/common';
import { AuthModule } from './auth/auth.module';
import { AuthController } from './auth/auth.controller';

@Module({
  imports: [AuthModule],
  controllers: [AuthController],
})
export class AppModule {}

注意事项

  1. 需要在Google开发者平台创建OAuth客户端ID和密钥
  2. 可根据需要替换其他OAuth提供商(如Facebook、GitHub等)
  3. 生产环境应使用HTTPS
  4. 建议使用JWT或其他方式管理会话而不是直接返回accessToken

以上是基本实现,实际项目中可能需要添加更多功能如用户数据库存储、JWT生成等。

回到顶部