How to use Tencent slider verification code in Vue3+Vue-cli4 project

How to use Tencent slider verification code in Vue3+Vue-cli4 project

Introduction:

Compared with traditional image verification codes, the slider verification code has the following advantages:

  • The server does not need to verify the specific verification of the verification code, the server only needs to verify the verification result.
  • We don't need to understand the implementation of the verification code, nor do we need to implement it specifically.
  • The security level of the slider verification code is much higher than that of the traditional verification code.
  • ...

Since there is a lack of information on how to apply Tencent's slider verification code in the combined API in Vue3 on the Internet and Tencent API documents, this tutorial is provided. I am not an expert in Vue, and my understanding of Vue is only at the level of basic use. If there are any mistakes, please point them out.

start:

First, we need to go to Tencent Cloud to apply for a graphics verification API and select our own usage scenario. After completing the steps, we will get CaptchaAppId and AppSecretKey. These two things are the parameters used by our server to verify the results later.

To use it in Vue3, you first need to import Tencent verification code js in the index.html of the public folder.

<script src="https://ssl.captcha.qq.com/TCaptcha.js"></script>

In the component that needs to use the slider verification code, bind a method for the login button. And add the following two fields ticket and randstr in the form object.

Here is my example written like this

export default {
    name: "Login",
    setup() {
        const loginForm = reactive({
            accountName: '',
            accountPassword: '',
            ticket: '',
            randstr: ''
        })
        return {
            loginForm
        }
    }
}

Login button binding method

export default {
    name: "Login",
    setup() {
        const loginForm = reactive({
            accountName: '',
            accountPassword: '',
            ticket: '',
            randstr: ''
        })
 
        const loginPost = () => {
 
            let captcha = new window.TencentCaptcha(config.app_id, res => {
                loginForm.randstr = res.randstr;
                loginForm.ticket = res.ticket;
 
                userLogin(loginForm).then(resp => {
 
                    if (resp.code === 200) {
                        //Logic after successful login} else {
                        //Logic after login failure}
                }).catch(() => {
                    ElMessage.error({
                        message: 'System error! Please try again later! '
                    })
                })
            })
            captcha.show();
        }
 
        return {
            loginPost,
            loginForm
        }
    }
}

The above is the code written in vue, but it only implements the operation of users completing the verification code. The specific final judgment logic must be implemented in our backend. We use Springboot on the back end to implement verification operations.

First, we need to introduce the Maven dependency of Tencent SDK

<!-- Tencent SDK-slider verification code dependency-->
<dependency>
  <groupId>com.tencentcloudapi</groupId>
  <artifactId>tencentcloud-sdk-java</artifactId>
  <version>4.0.11</version>
</dependency>

We create a new class in the utils package.

public class DescribeCaptchaResult {
    @Value("${Tencent.SecretId}")
    private String secretId;
 
    @Value("${Tencent.SecretKey}")
    private String secretKey;
 
    @Value("${Tencent.CaptchaAppId}")
    private int captchaAppId;
 
    @Value("${Tencent.AppSecretKey}")
    private String appSecretKey;
 
    public JSONObject getTencentCaptchaResult(String ticket, String randstr, String userIp) {
        try {
            // Instantiate an authentication object. The parameters need to be passed in the Tencent Cloud account secretId and secretKey. Here, you also need to pay attention to the confidentiality of the key pair. // The key can be obtained at https://console.cloud.tencent.com/cam/capi. Credential cred = new Credential(secretId, secretKey);
            // Instantiate an http option, optional, you can skip HttpProfile if there is no special requirement httpProfile = new HttpProfile();
            httpProfile.setEndpoint("captcha.tencentcloudapi.com");
            // Instantiate a client option, optional, you can skip ClientProfile if there is no special requirement clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // Instantiate the client object to request the product, clientProfile is optional CaptchaClient client = new CaptchaClient(cred, "", clientProfile);
            //Instantiate a request object. Each interface will correspond to a request object DescribeCaptchaResultRequest req = new DescribeCaptchaResultRequest();
            req.setCaptchaType(9L);
            req.setTicket(ticket);
            req.setRandstr(randstr);
            req.setUserIp(userIp);
            req.setCaptchaAppId((long) captchaAppId);
            req.setAppSecretKey(appSecretKey);
            // The returned resp is an instance of DescribeCaptchaResultResponse, corresponding to the request object DescribeCaptchaResultResponse resp = client.DescribeCaptchaResult(req);
            // Output the string in JSON format return JSONObject.parseObject(DescribeCaptchaResultResponse.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            throw new ServiceException(e.getMessage());
        }
    }
}

The following is a breakdown of the parameters required by this class.

parameter Analysis
secretId SecretId is the API key ID of your Tencent Cloud account (recommended to use a sub-account for authorization)
secretKey SecretKey is the API key of your Tencent Cloud account (it is recommended to use a sub-account for authorization)
captchaAppId captchaAppId is the Tencent verification code API key you applied for
appSecretKey appSecretKey is the Tencent verification code API key you applied for
ticket Ticket is the parameter returned after the verification code of the front-end slider is verified
randstr randstr is the parameter returned after your front-end slider verification code verification
userIp userIp is the IP obtained by your business layer
After providing the parameters and sending them, a data of type DescribeCaptchaResultResponse will be returned. We will convert it to FastJson's JSONObject type for parsing. The returned data structure is as follows:

{
"Response": {
  "RequestId": "3b61a17b-cb38-470e-802c-b6242faf81ac",
  "CaptchaCode": 1,
  "CaptchaMsg": "OK",
  "EvilLevel": 0,
  "GetCaptchaTime": 1583749870
},
"retcode": 0,
"retmsg": "success"
}

For other specific parameters, please refer to Tencent API documentation: https://cloud.tencent.com/document/product/1110/36926

I read the value of CaptchaCode here. If the value is 1, the verification code is successfully verified. If it is not 1, the verification fails.

//Verify the verification code JSONObject tencentCaptchaResult = captchaResult.getTencentCaptchaResult(ticket, randstr, clientIp);
 
int captchaCode = Integer.parseInt(tencentCaptchaResult.getString("CaptchaCode"));
 
 
if (captchaCode != 1) {
    throw new ServiceException("Verification code error!");
}
//...Subsequent business logic

Follow-up

In Tencent Cloud, you can also set more things for the verification code, such as the theme of the verification code, the scene configuration of the verification code, the level of malicious interception of the verification code, etc. .

You can also see the number of verification code requests in the background

I feel that the backend and frontend can be further encapsulated to make the code more concise. Alibaba Cloud has other new verification codes that I haven't tried yet. I personally feel that Tencent's verification code is pretty good to use, but the API documentation is a bit poor and there is very little information.

This is the end of this article about how to use Tencent slider verification code in Vue3+Vue-cli4 project. For more relevant vue Tencent slider verification code content, please search 123WORDPRESS.COM's previous articles 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+elementui realizes dragging the slider puzzle verification
  • Vue implements mobile slider verification
  • Vue implements slider verification when logging in
  • Practice of integrating Vue with Alibaba Cloud for slider verification
  • Vue implements simple slider verification
  • Use konva and vue-konva libraries to implement drag slider verification function
  • VUE access Tencent verification code function (slider verification) memo
  • Vue implements the drag slider verification function (only css+js without background verification steps)
  • vue-cli custom directive directive add validation slider example
  • How to encapsulate the image slider verification component in Vue

<<:  How to clear default styles and set common styles in CSS

>>:  HTML basic syntax is convenient for those who are just starting to learn HTML

Recommend

Best way to replace the key in json object

JSON (JavaScript Object Notation, JS Object Notat...

Implementation of master-slave replication in docker compose deployment

Table of contents Configuration parsing Service C...

Example operation MySQL short link

How to set up a MySQL short link 1. Check the mys...

Vue implements the method example of tab routing switching component

Preface This article introduces the use of vue-ro...

Detailed example of Linux all-round system monitoring tool dstat

All-round system monitoring tool dstat dstat is a...

A complete guide to the Docker command line (18 things you have to know)

Preface A Docker image consists of a Dockerfile a...

Detailed explanation of the TARGET attribute of the HTML hyperlink tag A

The hyperlink <a> tag represents a link poin...

How to implement an array lazy evaluation library in JavaScript

Table of contents Overview How to achieve it Spec...

The table merges cells and the img image to fill the entire td HTML

Source code (some classes deleted): Copy code The ...

Drop-down menu implemented by HTML+CSS3+JS

Achieve results html <div class="containe...

CentOS 8 is now available

CentOS 8 is now available! CentOS 8 and RedHat En...

How to set up vscode remote connection to server docker container

Table of contents Pull the image Run the image (g...