Implementation of vue+drf+third-party sliding verification code access

Implementation of vue+drf+third-party sliding verification code access

1. Background

Recently, the login function + verification code requirement was used in project development exercises. Verification codes are generally divided into three types: picture verification code, SMS verification code, and sliding verification code. The relevant implementation ideas are as follows

Image verification code

The implementation of the image verification code can be implemented with the help of the relevant methods of the third-party module pillow in python (I will write an article when I have time)

SMS verification code

The main idea of ​​SMS verification code is to send SMS to the mobile phone by calling the third-party SMS interface, receive the user input and compare it with the random number string generated by the system

Slide verification code

Sliding verification codes are generally provided by third-party verification code service providers, such as Tencent Waterproof Wall, JiTian Verification, etc. Compared with our own verification code, third-party verification code is more secure and reliable

This article takes Tencent Waterproof Wall as an example to record the access to a third-party sliding verification code service in a front-end and back-end separation project of a combination of vue and drf

2. Verification process

The front-end and back-end call sequence diagram of verification is as follows (the picture comes from the official document of Tencent verification code)

3. Create verification

First, log in to the Tencent Cloud console to create a cloud API key. In the left navigation bar, select [Access Management] > [API Key Management] to enter the API Key Management page and click [New Key] to create a key.

Then enter the verification code console, click [New Verification], enter the verification name, verification domain name, verification channel (Web or mini program plug-in) and verification scenario according to your needs, and after filling in, click [OK] to complete the verification creation.

Finally, check the resource information you applied for.

4. Front-end code

4.1 Add core js files

Import the front-end core js file of the waterproof wall into index.html in the project root directory using script tag

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <script src="https://ssl.captcha.qq.com/TCaptcha.js"></script>
    <title>opsweb</title>
  </head>
  <body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>


Or import it in src/main.js Before import , you need to download the core js file above to the project static file directory

// Import the core js file of the waterproof wall verification code import "../static/js/TCaptcha";

4.2 Add configuration

Add configuration in src/settings.js

export default {
  HOST: 'http://opsapi.ssgeek.com:8000', // backend api address TC_captcha:{
    app_id: "2020427221", // Tencent Waterproof Wall APPID configuration},
}


4.3 Component Modification

Modify the login page vue component Login.vue , bind the login button to the custom method of verification code display, trigger the verification code request first and then trigger the login

template

<template>
<!--Login content begins-->
<div class="inp" v-if="login_type==0">
  <input v-model="username" type="text" placeholder="username" class="user">
  <input v-model="password" type="password" name="" class="pwd" placeholder="password">
  <div class="rember">
    <p>
      <input v-model="remember_me" type="checkbox" class="no" name="a"/>
      <span>Remember password</span>
    </p>
  </div>
  <button class="login_btn" @click="show_captcha">Login</button>
<!--End of login content-->
</div>
</template>


script part

<script>
export default {
  name: 'Login',
  data() {
    return {
      login_type: 0,
      remember_me: false,
      username: "",
      password: "",
    }
  },
  methods: {
    show_captcha() {
      var captcha1 = new TencentCaptcha(this.$settings.TC_captcha.app_id, res=> {
        /*
        res:
        appid: "2020427221" # APPID of the verification code
        randstr: "@GCV" # Random string to prevent duplication ret: 0 # 0 means the user operation is successful, 2 means the user actively closes the verification code window ticket: "" # The ticket after verification is provided to the backend and will be processed in the verification code server */
        // console.log(res);
        this.$axios.get(`${this.$settings.HOST}/users/captcha/`, {
          params:{
            ticket: res.ticket,
            randstr: res.randstr,
          }
        }).then(response=>{
          if(response.data.detail){
            // Continue login processing this.login();
          }
        }).catch(error=>{
          this.$message.error("Sorry, verification code failed!");
        });
      });
      captcha1.show();
    },
    login() {
      // Determine whether the user enters a username or password, otherwise prompt the user to enter if (!this.username) {
        this.$message.error('Please enter your username!')
      } else if (!this.password) {
        this.$message.error('Please enter your password!')
      } else {
        // Submit a post request with username and password this.$axios.post(`${this.$settings.HOST}/users/login/`, {
          username: this.username,
          password: this.password,
        }).then((res) => {
          //Store token
          if (this.remember_me) {
            localStorage.token = res.data.token;
            sessionStorage.removeItem('token')
          } else {
            sessionStorage.token = res.data.token;
            localStorage.removeItem('token')
          }
          // Jump to the home page this.$router.push('/hippo/showcenter')
        }).catch((error) => { // Capture the error returned by the request, 4xx, 5xx
          this.$message.error('The username or password is incorrect, please re-enter!')
        })
      }
    },
  },
};

5. Backend code

For relevant operation instructions, please refer to the official example: https://007.qq.com/python-access.html

5.1 Add configuration

Configure the verification information viewed by Tencent Verification Code Console to the configuration file of the DRF backend code

# Tencent waterproof wall configuration TENCENT_CAPTCHA = {
    "GATEWAY": "https://ssl.captcha.qq.com/ticket/verify", # Verification code verification address "APPID": "2020427221", # APPID of the verification code application
    "App_Secret_Key": "0mnAr1EpNTjm63fQgKPU87w**", # AppSecretKey of the verification code application
}


5.2 Receive verification and return

Write a common class view of the user verification code in the user app

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.conf import settings
from urllib.parse import urlencode
from urllib.request import urlopen
import json
import ssl


# Create your views here.
class CaptchaAPIView(APIView):
    """Verification code"""
    ssl._create_default_https_context = ssl._create_unverified_context

    def get(self, request):
        """Receive verification code information submitted by the client"""
        params = {
            "aid": settings.TENCENT_CAPTCHA.get("APPID"),
            "AppSecretKey": settings.TENCENT_CAPTCHA.get("App_Secret_Key"),
            "Ticket": request.query_params.get("ticket"),
            "Randstr": request.query_params.get("randstr"),
            "UserIP": request._request.META.get("REMOTE_ADDR")
        }
        # Convert the dictionary data into the query string format of the address bar# aid=xxx&AppSecretKey=xxx&xxxxx
        params = urlencode(params)
        # print(params)
        url = settings.TENCENT_CAPTCHA.get("GATEWAY")
        # Send an http get request f = urlopen("%s?%s" % (url, params))
        # https://ssl.captcha.qq.com/ticket/verify?aid=xxx&AppSecretKey=xxx&xxxxx
        # f.read() Read the response information content = f.read()
        res = json.loads(content)
        # print(res)
        if int(res.get("response")) == 1:
            # Verification successful return Response({"detail": 1})
        else:
            # Verification failed return Response({"detail": 0}, status=status.HTTP_400_BAD_REQUEST)

5.3 Add url routing

Finally, add the backend url routing for the frontend to send requests

from django.urls import path
from rest_framework_jwt.views import obtain_jwt_token
from . import views

urlpatterns = [
    path('login/', obtain_jwt_token),
    path('captcha/', views.CaptchaAPIView.as_view()), # Verification code verification]

6. Run the test

The final effect is as follows

In the background of Tencent verification code, you can see detailed request information chart

This is the end of this article about the implementation of vue+drf+third-party sliding verification code access. For more relevant vue+drf+third-party sliding verification code access content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue implements login sliding puzzle verification
  • Vue implements picture sliding verification
  • Vue implements sliding verification bar
  • Vue implements sliding verification function
  • How does Vue call Tencent Cloud's sliding verification code in the project
  • Detailed explanation of the usage of sliding verification code of Vue plug-in
  • Vue plugin sliding verification code
  • Vue implements sliding verification from the bottom to the end
  • Use Vue to implement the sliding verification code function
  • Vue custom development sliding picture verification component

<<:  MySQL master-slave synchronization, implementation principle of transaction rollback

>>:  Detailed explanation of the processing of the three Docker Nginx Logs

Recommend

WeChat applet realizes chat room function

This article shares the specific code of WeChat a...

About the pitfall record of Vue3 transition animation

Table of contents background Problem location Fur...

Detailed explanation of MySQL basic operations (Part 2)

Preface This article contains 1. Several major co...

Problems encountered by MySQL nested transactions

MySQL supports nested transactions, but not many ...

Getting the creation time of a file under Linux and a practical tutorial

background Sometimes we need to get the creation ...

W3C Tutorial (6): W3C CSS Activities

A style sheet describes how a document should be ...

C# implements MySQL command line backup and recovery

There are many tools available for backing up MyS...

Vue custom components use event modifiers to step on the pit record

Preface Today, when I was using a self-written co...

In-depth explanation of the locking mechanism in MySQL

Preface In order to ensure the consistency and in...

Some problems you may encounter when installing MySQL

Question 1: When entering net start mysql during ...

Teach you how to quickly enable self-monitoring of Apache SkyWalking

1. Enable Prometheus telemetry data By default, t...

Solution to the problem of not finding Tomcat configuration in Intelli Idea

I joined a new company these two days. The compan...

Detailed tutorial on running selenium+chromedriver on the server

1. Introduction I want to use selenium to scrape ...

Solve the cross-domain problem of Vue+SpringBoot+Shiro

Table of contents 1. Configure Vue front end 1. D...

How to automatically import Vue components on demand

Table of contents Global Registration Partial Reg...