首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Nestjs和Google Recaptcha

Nestjs和Google Recaptcha
EN

Stack Overflow用户
提问于 2021-01-13 00:01:30
回答 3查看 729关注 0票数 0

EN

回答 3

Stack Overflow用户

发布于 2021-10-25 14:02:18

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

代码语言:javascript
复制
// 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;
  }
}

接下来,您可以简单地在控制器上应用recaptcha保护。

代码语言:javascript
复制
// 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(){
  //
 }
}
票数 2
EN

Stack Overflow用户

发布于 2021-04-12 03:18:42

导入HttpModule

代码语言:javascript
复制
import { HttpModule, Module } from '@nestjs/common';

@Module({
    imports: [HttpModule],
    ...
})

然后创建一个服务来验证captcha值

注意::您必须从获取秘密/站点密钥(站点密钥将在客户端使用)

代码语言:javascript
复制
import { HttpService, Inject, Injectable } from "@nestjs/common";
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';
import { map } from 'rxjs/operators'

@Injectable()
export class CaptchaService {
    constructor(
        @Inject(REQUEST) private readonly request: Request,
        private httpService: HttpService) { }

    public validate(value:string): Promise<any> {
        const remoteAddress = this.request.socket.remoteAddress
        const secretKey = "XXXXXXXXX"
        const url = "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + value + "&remoteip=" + remoteAddress;

        return this.httpService.post(url).pipe(map(response => {
            return response['data']
        })).toPromise()
    }
    
}

然后在你的控制器中:

代码语言:javascript
复制
 const value="XXXXX" // client send this for you
 const result = await this.captchService.validate(value)
 if (!result.success) throw new BadRequestException()

客户端

如果你使用的是angular,你可以使用

票数 0
EN

Stack Overflow用户

发布于 2021-12-08 10:56:25

最初,我遵循了公认的答案,然后注意到有一种更简单的方法--我想分享它,以防它能帮助任何人。

有一个NestJS模块可以很容易地与ReCAPTCHA集成:https://github.com/chvarkov/google-recaptcha

  • 安装该模块。
  • 在您的AppModule中创建类似以下内容:

代码语言:javascript
复制
    const googleRecaptchaFactory = (
      applicationConfigService: ApplicationConfigService,
    ) => ({
      secretKey: applicationConfigService.auth.recaptcha.secretKey,
      response: (req) => req.headers.recaptcha || '',
      skipIf: applicationConfigService.auth.recaptcha.bypassVerification,
    });
    
    @Module({
      controllers: [/* ... */],
      imports: [
        /* ... */
        GoogleRecaptchaModule.forRootAsync({
          imports: [],
          inject: [ApplicationConfigService],
          useFactory: googleRecaptchaFactory,
        }),
      ],
      providers: [/* ... */],
      exports: [/* ... */],
    })
    export class Module {}

  • 现在,在您的控制器中,使用@Recapcha防护。

您可以在链接的Github中找到整个集成过程的文档。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65687512

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档