Implementation of Short Message Verification Code Verification by SpringBoot

This article is welcomed to reprint, please indicate the source, thank you ~ (Author: Drinking does not ride Colton_Null)
from CSDN

Refer to another blog post about sending verification codes for Aliyun SMS service.
Springboot Realizes Aliyun Communication Short Message Service and Sends Short Message Verification Code
This paper will explain the idea of verification code.

thinking

After the user enters the phone number, click the button to get the authentication code. And set the cooling time to prevent users from frequent clicks.
The background generates the authentication code and sends it to the user's mobile phone. The MD5 value is generated according to the authentication code, time and a series of custom keys, and the time is also transmitted back to the front end.
After the user enters the authentication code, the authentication code and time are transmitted to the background. The background first uses the current time minus the time passed from the front desk to verify whether the timeout is over. If there is no timeout, the MD5 value generated by the user's input verification code + time + custom key is compared with the previous MD5 value. If it is equal, the verification code passes. If it is not equal, the verification code input error fails.
The principle is somewhat like solving equations:
Xz gets A through an irreversible operation, and passes y and A to the user. z is retained in the background. After the user fills in x1, x1yA is returned to the background. The background uses x1yz to get A1 through irreversible operation. If A1 and A are equal, the verification code passes through.

Implementation of Front End

This example is based on BootStrap. There is a BootStrap style in html code. If you don't want to use BootStrap, you can remove the class style. The effect is shown in the figure.

The html code is as follows:

<div class="form-group has-feedback">
    <input type="tel" class="form-control"  id="phone" placeholder="Please enter your cell phone number." maxlength=11>
    <span class="glyphicon glyphicon-earphone form-control-feedback"></span>
</div>
<div class="row">
    <div class="col-xs-6 pull_left">
        <div class="form-group">
            <input class="form-control" id="msg_num" placeholder="Please enter the verification code.">
        </div>
    </div>
    <div class="col-xs-6 pull_center">
        <div class="form-group">
            <input type="button" class="btn btn-block btn-flat" id="verify_refresh" onclick="getMsgNum(this)" value="Free access to authentication codes">
        </div>
    </div>
</div>

<div class="col-xs-12 pull_center">
    <button type="button" class="btn btn-block btn-flat" onclick="validateNum()">Verification</button>
</div>

js code (based on jQuery)

var messageData;
var wait = 120; // Short Message Verification Code 120 seconds before the next one can be obtained

/**
 * Get the authentication code
 * @param that
 */
function getMsgNum(that) {
    var phoneNumber = $('#phone').val();
    setButtonStatus(that); // Set the button countdown
    var obj = {
        phoneNumber: phoneNumber
    };

    $.ajax({
        url: httpurl + '/sendMsg', // Background Short Message Delivery Interface
        type: 'POST',
        dataType: 'json',
        contentType: "application/json",
        async: false, //false synchronization
        data: JSON.stringify(obj),
        xhrFields: {
            withCredentials: true
        },
        success: function (result) {
            if(result.code == '200') {
                messageData = result.data;
            }else {
                alert("Error code:" + data.code + "  error message:" + data.message);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(XMLHttpRequest.status);
            console.log(XMLHttpRequest.readyState);
            console.log(textStatus);
        }
    });
}
/**
 * Set button status
 */
function setButtonStatus(that) {
    if (wait == 0) {
        that.removeAttribute("disabled");
        that.value="Free access to authentication codes";
        wait = 60;
    } else {
        that.setAttribute("disabled", true);
        that.value=wait+"It can be re-sent in seconds";
        wait--;
        setTimeout(function() {
            setButtonStatus(that)
        }, 1000)
    }
}

/**
* Registration button
*/
function validateNum() {
    var data = {
        msgNum: inputMsgNum,
        tamp: messageData.tamp,
        hash: messageData.hash
    };

    $.ajax({
        url: httpurl + '/validateNum', // Verification interface
        type: 'POST',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(data),
        async: false, //false synchronization
        success: function (data) {
           //Business process
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(XMLHttpRequest.status);
            console.log(XMLHttpRequest.readyState);
            console.log(textStatus);
        }
    });
}

The setButtonStatus() method is used to set the button's cooling state. The effect is as follows

Realization of Background

private static final String KEY = "abc123"; // KEY is a custom key

@RequestMapping(value = "/sendMsg", method = RequestMethod.POST, headers = "Accept=application/json")
public Map<String, Object> sendMsg(@RequestBody Map<String,Object> requestMap) {
String phoneNumber = requestMap.get("phoneNumber").toString();
String randomNum = CommonUtils.createRandomNum(6);// Generating Random Numbers
SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
Calendar c = Calendar.getInstance();
c.add(Calendar.MINUTE, 5);
String currentTime = sf.format(c.getTime());// After 5 minutes of generation, user checks expire
sengMsg(); //The method of sending short message verification code is executed here.
String hash =  MD5Utils.getMD5Code(KEY + "@" + currentTime + "@" + randomNum);//Generate MD5 value
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("hash", hash);
resultMap.put("tamp", currentTime);
return resultMap; //Return hash value and tamp time to the front end
}

@RequestMapping(value = "/validateNum", method = RequestMethod.POST, headers = "Accept=application/json")
public Map<String, Object> validateNum(@RequestBody Map<String,Object> requestMap) {
String requestHash = requestMap.get("hash").toString();
String tamp = requestMap.get("tamp").toString();
String msgNum = requestMap.get("msgNum").toString();
String hash = MD5Utils.getMD5Code(KEY + "@" + tamp + "@" + msgNum);
if (tamp.compareTo(currentTime) > 0) {
if (hash.equalsIgnoreCase(requestHash)){
//Check success
}else {
//Validation code incorrect, check failure
}
} else {
// overtime
}
}

summary

This is the verification code verification method based on SpringBoot. I hope this article can help you.

Keywords: JSON SpringBoot Mobile JQuery

Added by dave420 on Mon, 03 Jun 2019 23:14:09 +0300