发布于 2021-10-25 14:02:18
我通过创建一个独立的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;
}
}接下来,您可以简单地在控制器上应用recaptcha保护。
// 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(){
//
}
}发布于 2021-04-12 03:18:42
导入HttpModule
import { HttpModule, Module } from '@nestjs/common';
@Module({
imports: [HttpModule],
...
})然后创建一个服务来验证captcha值
注意::您必须从获取秘密/站点密钥(站点密钥将在客户端使用)
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()
}
}然后在你的控制器中:
const value="XXXXX" // client send this for you
const result = await this.captchService.validate(value)
if (!result.success) throw new BadRequestException()客户端
如果你使用的是angular,你可以使用
发布于 2021-12-08 10:56:25
最初,我遵循了公认的答案,然后注意到有一种更简单的方法--我想分享它,以防它能帮助任何人。
有一个NestJS模块可以很容易地与ReCAPTCHA集成:https://github.com/chvarkov/google-recaptcha。
AppModule中创建类似以下内容: 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中找到整个集成过程的文档。
https://stackoverflow.com/questions/65687512
复制相似问题