Po pierwsze należy wygenerować indywidulany dla domeny (może być też localhost dla testów lokalnych) sitekey i secret –> Google reCAPTCHA
Integracja po stronie klienta
W formularzu dodajemy kod reCAPTCHA z wygenerowanym sitekey
<div class="form-group"> <div class="g-recaptcha" data-sitekey="6Lf7anUUAAAAAHobMeDJkbR_xxxasasasa"></div> </div>
Następnie w komponencie z formularzem w metodzie ngOnInit() dodajemy do strony skrypt z api reCAPTCHA. Jeśli skrypt zostałby dodany do index.html, to reCAPTCHA pojawiałaby się tylko po odświeżeniu strony.
ngOnInit(){ this.addScript(); } addScript() { let script = document.createElement('script'); script.src = 'https://www.google.com/recaptcha/api.js'; script.async = true; script.defer = true; document.body.appendChild(script); }
Przed wysłaniem formularza należy sprawdzić czy pole “Nie jestem robotem” zostało zaznaczone.
onSubmit() { this.submitted = true; const response = grecaptcha.getResponse(); if (response.length === 0) { alert('Recaptcha not verified.'); return; } this.save(); } save() { this.accountService.createNewUser(this.registerForm.value, grecaptcha.getResponse()) .subscribe( data => { console.log(data); }, error => { console.log(error); }) }
Integracja po stronie serwera – tutaj przyda się przydzielony wcześniej kod secret
@PostMapping("/new") @ResponseStatus(HttpStatus.CREATED) public void createUser(@RequestBody UserDTO user, @RequestParam(name="response") String recaptchaResponse) { captchaVerification.verify(recaptchaResponse); userRepository.findByEmailIgnoreCase(user.getEmail()) .ifPresent(u -> {throw new ResourceExistsException("User with login: "+user.getEmail()+" exist");}); User createdUser = userService.createUser(user); }
Przed dodaniem nowego użytkownika do bazy danych należy sprawdzić poprawność recaptchaResponse, wysyłając zapytanie przez recaptcha api.
import java.net.URI; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service("captchaVerification") public class CaptchaVerification { @Autowired private CaptchaSettings captchaSettings; public void verify(String response) { URI verifyUri = URI.create(String.format( "https://www.google.com/recaptcha/api/siteverify?secret=%s&response=%s", captchaSettings.getSecret(), response)); RestTemplate restTemplate = new RestTemplate(); GoogleResponse googleResponse = restTemplate.getForObject(verifyUri, GoogleResponse.class); if(!googleResponse.isSuccess()) { throw new InvalidRecaptchaException(); } } }
Sitekey i Secret umieszczone są w application.properties
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "google.recaptcha.key") public class CaptchaSettings { private String site; private String secret; public String getSite() { return site; } public void setSite(String site) { this.site = site; } public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } }
Klasa GoogleResponse jest schematem reprezentującym odpowiedź przesłaną od Google Api i pomaga stwierdzić poprawność walidacji reCAPRTCHA.
import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @JsonPropertyOrder({ "success", "challenge_ts", "hostname", "error-codes" }) public class GoogleResponse { @JsonProperty("success") private boolean success; @JsonProperty("challenge_ts") private String challengeTs; @JsonProperty("hostname") private String hostname; @JsonProperty("error-codes") private ErrorCode[] errorCodes; @JsonIgnore public boolean hasClientError() { ErrorCode[] errors = getErrorCodes(); if(errors == null) { return false; } for(ErrorCode error : errors) { switch(error) { case InvalidResponse: case MissingResponse: return true; } } return false; } static enum ErrorCode { MissingSecret, InvalidSecret, MissingResponse, InvalidResponse; private static Map<String, ErrorCode> errorsMap = new HashMap<String, ErrorCode>(4); static { errorsMap.put("missing-input-secret", MissingSecret); errorsMap.put("invalid-input-secret", InvalidSecret); errorsMap.put("missing-input-response", MissingResponse); errorsMap.put("invalid-input-response", InvalidResponse); } @JsonCreator public static ErrorCode forValue(String value) { return errorsMap.get(value.toLowerCase()); } } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public String getChallengeTs() { return challengeTs; } public void setChallengeTs(String challengeTs) { this.challengeTs = challengeTs; } public String getHostname() { return hostname; } public void setHostname(String hostname) { this.hostname = hostname; } public ErrorCode[] getErrorCodes() { return errorCodes; } public void setErrorCodes(ErrorCode[] errorCodes) { this.errorCodes = errorCodes; } }
Powyższe fragmenty kodu są też zawarte w projekcie Clinic (clinic-server, clinic-client) na GitHub >>tutaj<<
You choose peace or war?
There is certainly a great deal to learn about this issue. I like all of the points you made. Reinaldo Spyres
Post writing is also a excitement, if you be familiar with then you can write if not it is difficult to write. Donovan Gift
Excellent write-up. I absolutely appreciate this site. Wilber Anagnostou
There is definately a great deal to know about this subject. I like all the points you have made. Winford Gruenes
This post provides clear idea in favor of the new viewers of blogging, that actually how to do blogging and site-building. Darwin Palczynski
You made some decent points there. I did a search on the topic and found most persons will go along with with your site. Deandre Vis
Have you ever considered publishing an ebook or guest authoring on other blogs? I have a blog based on the same subjects you discuss and would really like to have you share some stories/information. I know my viewers would value your work. If you’re even remotely interested, feel free to shoot me an e-mail.
�Ok stop. Come with me.� I said the game now changing.
I like what you guys are up too. Such intelligent work and reporting! Keep up the excellent works guys I’ve incorporated you guys to my blogroll. I think it will improve the value of my site :).
�Well that answers that. I live at home, Mum and Dad are there so let�s go back to your place.� she said as she reached in and grabbed a towel
Antifa is the prefect example of what fascists are. William Chitty
As soon as I noticed this internet site I went on reddit to share some of the love with them. Dominic Larmon
I am truly grateful to the holder of this website who has shared this fantastic article at at this place. Linwood Niemann
So you are a man or woman?
Where there is a will, there is a way.
This piece of writing is genuinely a nice one it assists new internet people, who are wishing in favor of blogging. Lynwood Sedgwick
Your Blog is very nice. Wish to see much more like this.
Good� i really like your blog�
Way cool, some valid points! I appreciate you making this article available, the rest of the site is also high quality. Have a fun.
Wow, amazing blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your site is excellent, as well as the content!
What’s Going down i’m new to this, I stumbled upon this I have discovered It absolutely helpful and it has aided me out loads. I am hoping to give a contribution & help other customers like its helped me. Great job.
Great content and thank you to the author.
This is my first time pay a visit att here and i am actually pleassant to read everthing at one place. Sam Kilimnik
I every time used to study paragraph in news papers but now as I am a user of net thus from now
I am using net for articles or reviews, thanks to web.
Some truly select blog posts on this web site, saved to bookmarks.
Would you be all in favour of exchanging links?
We are a group of volunteers and starting a new scheme in our community. Your web site offered us with valuable information to work on. You’ve done a formidable job and our entire community will be thankful to you.
I think the admin of this site is truly working hard for his website, since here every material is quality based stuff. Donte Armson
Nothing has been the same since your ex broke up with you. Rickie Altiery
I enjoy, cause I found exactly what I was having a look for. Paul Rearden
100,000 Backlinks only $10,Subject to data from ahrefs.com.After paid $10 by PayPal (My PayPal:helloboy1979@gmail.com),Tell me your URL, email and comment content.I will complete the task within ten days.But It may take up to a month for the data updated from ahrefs.com.
You made various nice points there. I did a search on the issue and found nearly all persons will go along with with your blog.
I constantly emailed this webpage post page to all my contacts, for the reason that if like to read it then my friends will too. Bob Dompe
Way cool! Some extremely valid points! I appreciate you writing this post and also the rest of the site is very good. Marcelino Mihalkovic
Just make sure that thehow the money stays within your circle of friends. Ross Oakland
Hi, after reading this amazing paragraph i am also delighted to share my know-how here with colleagues. Cary Alhusseini