Here are a few steps how to add Google reCaptcha to JHipster app.
Let's assume that you have already a domain - it’s not possible to do it in test environment.
Add your site here: https://www.google.com/recaptcha/admin#list
And choose reCaptcha v.2 [Validate requests with the “I’m not a robot” checkbox].
You’ll get site key like ‘6LfedWkUhkjgkyUGkjhg1OxiWuJVu7_2PWnFID68’.
In index.html file add:
In index.html file add:
<script src='https://www.google.com/recaptcha/api.js?render=explicit" async defer'></script>
In register.component.html file add:
<div #recaptchaDiv></div>
Change:
<button type="submit" [disabled]="registerForm.form.invalid" class="btn btn-primary" jhiTranslate="register.form.button">Register</button>
to:
<button type="submit" [disabled]="registerForm.form.invalid || !recaptchaVerified" class="btn btn-primary" jhiTranslate="register.form.button">Register</button>
In register.component.ts file add on top:
recaptchaVerified: boolean; errormsg: string; @ViewChild('recaptchaDiv') recaptchaDiv: ElementRef; private _reCaptchaId: number; private SITE_ID = '6LfedWkUhkjgkyUGkjhg1OxiWuJVu7_2PWnFID68';
window['onloadCallback'] = this.onloadCallback.bind(this);
In ngOnInit() add:
this.recaptchaVerified = false;
Then add 3 methods:
onloadCallback(response) { // console.log('verifyCallback=' + response); const grecaptcha = (window as any).grecaptcha; if (grecaptcha) { this._reCaptchaId = grecaptcha.render(this.recaptchaDiv.nativeElement, { 'sitekey': this.SITE_ID, 'callback': (resonse) => this.reCapchaSuccess(resonse), 'expired-callback': () => this.reCapchaExpired() }); } } reCapchaSuccess(data: any) { if (data) { // console.log('Congratulation! reCAPTCHA verified.'); this.recaptchaVerified = true; } } reCapchaExpired() { // console.log('Oops! reCAPTCHA expired.'); this.recaptchaVerified = false; }
Thanks to: https://stackoverflow.com/questions/48902711/how-to-add-recaptcha-in-angular-2-application
Brak komentarzy:
Prześlij komentarz