1. BackgroundRecently, 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 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 2. Verification processThe 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 verificationFirst, 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 code4.1 Add core js files Import the front-end core <!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 // Import the core js file of the waterproof wall verification code import "../static/js/TCaptcha"; 4.2 Add configuration Add configuration in 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 <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> 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 codeFor relevant operation instructions, please refer to the official example: https://007.qq.com/python-access.html 5.1 Add configurationConfigure 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 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 routingFinally, 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 testThe 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:
|
<<: MySQL master-slave synchronization, implementation principle of transaction rollback
>>: Detailed explanation of the processing of the three Docker Nginx Logs
Installation The required documents are provided ...
Custom Image FAQ How to view the data disk? You c...
Before reading this article, I hope you have a ba...
Table of contents Problem Description What is Vue...
Download link: Operating Environment CentOS 7.6 i...
Table of contents vue - Use swiper plugin to impl...
1. Create a configuration file directory cd /home...
Some attributes about elements In the daily devel...
Software and hardware environment centos7.6.1810 ...
The first step is to check the version number and...
Table of contents Nginx load balancing configurat...
Similar structures: Copy code The code is as foll...
Table of contents PXE implements unattended batch...
Table of contents MySQL Shell import_table data i...
a href="#"> After clicking the link, ...