Nestjs 和 Google Recaptcha

Tah*_*son 4 recaptcha nestjs

我正在尝试使用 Nestjs 实现 reCaptcha 的服务器端验证,我想知道是否应该将其实现为模块或模块服务(例如自行编写的用户身份验证模块),这需要使用 reCaptcha。

Rob*_*per 7

我通过创建一个单独的 RecaptchaGuard 解决了这个问题。

// recaptcha.guard.ts
import {
  Injectable,
  CanActivate,
  ExecutionContext,
  HttpService,
  ForbiddenException,
} from "@nestjs/common";

@Injectable()
export class RecaptchaGuard implements CanActivate {
  constructor(private readonly httpService: HttpService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const { body } = context.switchToHttp().getRequest();

    const { data } = await this.httpService
      .post(
        `https://www.google.com/recaptcha/api/siteverify?response=${body.recaptchaValue}&secret=${process.env.RECAPTCHA_SECRET}`
      )
      .toPromise();

    if (!data.success) {
      throw new ForbiddenException();
    }

    return true;
  }
}
Run Code Online (Sandbox Code Playgroud)

接下来,您只需在控制器上应用验证码防护即可。

// app.controller.ts
import { Controller, Post, UseGuard } from '@nestjs/common';
import { RecaptchaGuard } from './recaptcha.guard.ts'
    
@Controller()
export class AppController {

 @Post()
 @UseGuard(RecaptchaGuard)
 async postForm(){
  //
 }
}
Run Code Online (Sandbox Code Playgroud)