Skip to main content

Kotlin + Spring + Vue: Spam Protection (reCAPTCHA)

We have a registration feature,
that means now it's time to think about spam protection. Let's do it using Google powerful tool - reCAPTCHA.

reCAPTCHA is a CAPTCHA-like system designed to establish that a computer user is human (normally in order to protect websites from bots) and, at the same time, assist in the digitization of books or improve machine learning.
Wikipedia

Objectives

  • Enable reCAPTCHA at the pages of SignUp and SignIn
  • Make server-side verification

Setting Up reCAPTCHA

  1. Visit Google reCAPTCHA admin panel. 
  2. Click Add new site.
  3. Use the following settings:


Save key and secret (and it's better to copy to application.settings):


Backend

Environment Variables

Add the following environment variables (or add these arguments to the startup settings):

GOOGLE_RECAPTCHA_KEY_SITE
GOOGLE_RECAPTCHA_KEY_SECRET



application.properties 

Add the relevant application properties:

google.recaptcha.key.site=${GOOGLE_RECAPTCHA_KEY_SITE}
google.recaptcha.key.secret=${GOOGLE_RECAPTCHA_KEY_SECRET}


pom.xml

Add a new dependency to pom.xml:

<!-- Unirest -->
<dependency>
     <groupId>com.mashape.unirest</groupId>
     <artifactId>unirest-java</artifactId>
     <version>1.4.9</version>
</dependency>



Models

Update LoginUser and NewUser by adding new String field - recaptchaToken:
LoginUser:
NewUser:

Service

Add a service to validate reCAPTCHA tokens to /service:

AuthController

Update AuthController in following way - validating the token from request:

import com.kotlinspringvue.backend.service.ReCaptchaService



@Autowired
lateinit var captchaService: ReCaptchaService



if (!captchaService.validateCaptcha(loginRequest.recaptchaToken!!)) {
     return ResponseEntity(ResponseMessage("Validation failed (ReCaptcha v2)"),
     HttpStatus.BAD_REQUEST)
}
else [if]...



if (!captchaService.validateCaptcha(newUser.recaptchaToken!!)) {
     return ResponseEntity(ResponseMessage("Validation failed (ReCaptcha v2)"),
     HttpStatus.BAD_REQUEST)
} else...



Frontend

First of all, install and save the reCAPTCHA package:

$ npm install --save vue-recaptcha


Then update <head> of your index.html (public/index.html) - add:

<script src="https://www.google.com/recaptcha/api.js?onload=vueRecaptchaApiLoaded&render=explicit" async defer></script>


SignIn.vue and SignUp.vue

Update <template>:

<b-button v-on:click="validateCaptcha" variant="primary">Login</b-button>

...

<vue-recaptcha
     ref="recaptcha"
     size="invisible"
     :sitekey="sitekey"
     @verify="onCapthcaVerified"
     @expired="onCaptchaExpired"
/>


Update <script>:

import VueRecaptcha from 'vue-recaptcha'



export default

components: { VueRecaptcha },

data() {

siteKey: 'site_key'

}


methods:

validateCaptcha() {

     this.$refs.recaptcha.execute()

},

onCapthcaVerified(recaptchaToken) {

     AXIOS.post(`/auth/signin`, {'username': this.$data.username, 'password': this.$data.password, 'recapctha_token': recaptchaToken})
     .then(response => {
          this.$store.dispatch('login', {'token': response.data.accessToken, 'roles': response.data.authorities, 'username': response.data.username});
          this.$router.push('/home')
     }, error => {
          this.showAlert(error.response.data.message);
  })
     .catch(e => {
     console.log(e);
            this.showAlert('Server error. Please, report this error website owners');
  })
},
onCaptchaExpired() {
   this.$refs.recaptcha.reset()
}




NOTE: do that both for SignIn.vue and SignUp.vue




Ways to Improve


Links


Comments

  1. I was reading some of your content on this website and I conceive this internet site is really informative ! Keep on putting up. anti captcha key

    ReplyDelete
  2. "very informative topic, keep sharing such wonderful posts with us, and I will subscribe for more useful updates from you.
    latest tech news"

    ReplyDelete

Post a Comment

Popular posts from this blog

Make Authentication More Secure With Cookies Email Registration Confirmation That's all for this year. See you in 2020!

Kotlin + Spring Boot + Vue.js: + Gradle

Hello, dear visitors! I added two new articles to the Fullstack section: Kotlin + Spring + Vue: Migration from Maven to Gradle Kotlin + Spring + Vue: Deploy to Heroku with Gradle I'll be glad if you will find then useful for yourself.

Kotlin + Spring Boot + Vue.js

Hello there! I've published my first set of articles about developing web applications using Kotlin , Spring Boot and Vue.js : Koltin + Spring Boot + Vue.js Here are the contents of this set: Introduction Start CI/CD REST API Database Connection Authentication Spam Protection (reCAPTCHA) Email