在网站登陆注册时常常需要用到验证码,来防止站点被攻击。
大概这个样子:
现在框架是前后端分离的,angular+webapi弄个验证码感觉有点麻烦 然后就找到google的reCAPTCHA 还挺好使的,记录一下: 地址:https://www.google.com/recaptcha/admin/create 填写注册信息:
一个在前端配置,一个再后端配置: 可以参考这里:https://developers.google.com/recaptcha/docs/invisible
普通html配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <html> <head> <title>reCAPTCHA demo: Simple page</title> <script src="https://www.google.com/recaptcha/api.js" async defer></script> <script> function onSubmit(token) { document.getElementById("demo-form").submit(); } </script> </head> <body> <form id='demo-form' action="?" method="POST"> <button class="g-recaptcha" data-sitekey="your_site_key" data-callback='onSubmit'>Submit</button> <br/> </form> </body> </html>
angular中使用: 安装ng-recaptcha
1 npm i ng-recaptcha --save
在表单中配置:
1 2 3 4 <re-captcha class="grecaptcha" #captchaRef="reCaptcha" siteKey="YOUR_KEY" size="invisible" (resolved)="$event && _submitForm($event,validateForm.value)"></re-captcha> <button nz-button (click)="captchaRef.execute()" (click)="savereCaptcha(captchaRef)" nzType="primary">登录</button>
ts代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 _submitForm(recaptchaId, value) { for (const i in this.validateForm.controls) { if (this.validateForm.controls.hasOwnProperty(i)) { this.validateForm.controls[i].markAsDirty(); } } this.isLoading = true; this.authenticationService.login(value.userName, value.password, recaptchaId) .subscribe( data => { this.isLoading = false; this.grecaptcha.reset(); // 刷新验证码 this.router.navigate([this.returnUrl]); }, error => { this.isLoading = false; this.error = true; this.grecaptcha.reset(); // 刷新验证码 }); } savereCaptcha(captchaRef) { this.grecaptcha = captchaRef.grecaptcha; }
.Net Core 后台校验,在登陆或注册的地方:
1 2 3 4 5 // 生产环境才校验验证码 公司网络有毒 ping www.recaptcha.net 经常不通 if (_env.IsProduction() && !await CheckReCAPTCHA(auth.recaptchaToken)) { return NotFound("Google reCaptcha validation failed"); }
检验方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 private async Task<bool> CheckReCAPTCHA(string recaptchaToken) { string baseUrl = _config["reCAPTCHA:baseUrl"]; string secretKey = _config["reCAPTCHA:secretKey"]; var values = new Dictionary<string, string> { { "secret", secretKey }, { "response",recaptchaToken } }; var content = new FormUrlEncodedContent(values); HttpClient httpClient = new HttpClient(); var response = await httpClient.PostAsync(baseUrl, content); var responseString = await response.Content.ReadAsStringAsync(); var obj = JObject.Parse(responseString); var status = (bool)obj.SelectToken("success"); return status; }
由于国内访问Google受限制,需要讲api地址改下:
将前端中JS的src 从
1 https://www.google.com/recaptcha/api.js
修改为
1 https://www.recaptcha.net/recaptcha/api.js
将后端的API 地址从
1 https://www.google.com/recaptcha/api/siteverify
换为
1 https://www.recaptcha.net/recaptcha/api/siteverify
参考:https://131.re/marchives/110
Google Api后挺好使的,效果也是超乎想象的