简体   繁体   English

使用 ng-recaptcha 将 Google reCaptcha v3 集成到 Angular 应用程序中

[英]Integrating Google reCaptcha v3 into Angular app with ng-recaptcha

I'd like to protect a register page from automatic submitions, so I decided to try reCaptcha v3.我想保护注册页面免受自动提交,所以我决定尝试 reCaptcha v3。 It's an Angular application, and I'm using ng-recaptcha module for easier integration.这是一个 Angular 应用程序,我使用ng-recaptcha模块来更轻松地集成。 I've set up a basic example on Stackblitz so you can test it online:我已经在 Stackblitz 上设置了一个基本示例,因此您可以在线测试它:

https://stackblitz.com/edit/angular-qk3jhr https://stackblitz.com/edit/angular-qk3jhr

I have a couple of doubts/problems:我有几个疑问/问题:

  1. If I write my valid Google key into the app.module.ts file, when I press the submit button, the this.recaptchaV3Service.execute call does nothing.如果我将有效的 Google 密钥写入app.module.ts文件,当我按下提交按钮时, this.recaptchaV3Service.execute调用什么也不做。 Is it because the app is not in the domain I stated when generating reCaptcha V3 keys?是因为该应用程序不在我在生成 reCaptcha V3 密钥时指定的域中吗? Also, if I write a wrong key, Google complains with the following error:另外,如果我写错了密钥,Google 会抱怨以下错误:

Error: Invalid site key or not loaded in api.js:错误:无效的站点密钥或未在 api.js 中加载:

  1. Once I'd get the token, what do i do with it?一旦我得到令牌,我该怎么办? I've read the ng-recaptcha documentation but I don't see anything about it.我已经阅读了 ng-recaptcha 文档,但我什么也没看到。 I mean, when I have the token, what do I need to do to check if it's valid and send the form?我的意思是,当我拥有令牌时,我需要做什么来检查它是否有效并发送表格?

Thanks in advance,提前致谢,

Finally, I got some time to try some things and I managed to make it work.最后,我有时间尝试一些事情,并设法让它发挥作用。 Basically, what I did is:基本上,我所做的是:

1 Generate a pair of keys for testing (setting 'localhost' in the domain). 1 生成一对用于测试的密钥(在域中设置“localhost”)。

2 In the client app, I've set up the ng-recaptcha module as explained in its page ( https://www.npmjs.com/package/ng-recaptcha#recaptcha-v3-usage-see-in-action ). 2 在客户端应用程序中,我已经按照其页面中的说明设置了ng-recaptcha模块( https://www.npmjs.com/package/ng-recaptcha#recaptcha-v3-usage-see-in-action ) . Then, from the user registration component (which I want to protect), I run the following code when pressing the 'Submit' button:然后,从用户注册组件(我想保护它),我在按下“提交”按钮时运行以下代码:

public beforeSubmittingForm(): void {
    this.recaptchaV3Service.execute('registerSubmit').subscribe(
        (token) => {
            // 'this.user' contains the data of the user we want to create. Add the received token
            this.user.recaptchav3_token = token;    

            this.submitForm();  // This sends the user data to the backend
        },
        (error) => {
            this.errors = [ 'Error trying to verify request (reCaptcha v3)' ];
        });
}

3 In the backend, in the user registration route, I use the axios library ( https://www.npmjs.com/package/axios ) to make a POST request to the Google verify service with the received token: 3 在后端,在用户注册路径中,我使用axios库( https://www.npmjs.com/package/axios )使用收到的令牌向 Google 验证服务发出 POST 请求:

try {
    var result = await axios.post("https://www.google.com/recaptcha/api/siteverify", {}, {
        params: {
            secret: recaptcha_api_key,  // Secret API key
            response: req.body.recaptchav3_token    // Received token from the frontend
        }
    });

    if(result.score < 0.5) {
        return res.status(403).json({ msg: 'Google Recaptcha error' });
    }
} catch(e) {
    return res.status(403).json({ msg: 'Error trying to verify the request' });
}
// Continue with the registration process...

Hope it helps, cheers!希望能帮到你,加油!

I'm not sure I understand the first question.我不确定我是否理解第一个问题。 If you use an invalid key then it's expected you'll get that error.如果您使用无效的密钥,那么预计您会收到该错误。 If you use the correct key for the correct domain, the token should be generated.如果您为正确的域使用正确的密钥,则应生成令牌。

For the 2nd question... there's really no need generate a token during ngOnInit() in this case because you're generating a token in your preSubmitForm() method, and that is sufficient.对于第二个问题......在这种情况下,真的不需要在ngOnInit()期间生成令牌,因为您在preSubmitForm()方法中生成了一个令牌, preSubmitForm()足够了。 As to what to do with the token, you will need to post it along with the rest of the form data to your server.至于如何处理令牌,您需要将它与表单数据的其余部分一起发布到您的服务器。 Then in your server-side code where the form submit is handled, make a request to the recaptcha API providing both the token and your secret key.然后在处理表单提交的服务器端代码中,向提供令牌和密钥的 recaptcha API 发出请求。

Take a look at Google's reCaptcha documentation in regard to server side validation.查看谷歌关于服务器端验证的 reCaptcha 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM