Step by step Vue + element front end application development (32) — Mobile SMS dynamic code login processing


In some systems, sometimes users forget their password and can realize the system login function by sending dynamic verification code to their mobile phone. This essay introduces how to combine the processing of SMS sending and caching module of back-end ABP framework to realize SMS dynamic code login processing.

The general login methods are divided into ordinary account login, dynamic password login, scanning QR code login and other methods. Other methods are not discussed here. The dynamic code login method is mainly introduced.

1. Sending and processing of SMS verification code

  I wrote in the first essay《SMS sending processing in the ABP framework includes the integration of Alibaba cloud SMS and ordinary SMS providers》This paper introduces how to use ABP framework to realize the sending and processing of short messages. Therefore, we can realize the login processing of dynamic password through short messages at the front and back ends.

Therefore, in the authorized login controller, we add the interface injection for SMS sending, as shown below.


Then, two interfaces are defined, one is the interface that sends the dynamic verification code to the user’s mobile phone, and the other is the login processing interface according to the user’s mobile phone and dynamic verification code.

Then we can add two methods to the authentication controller.

Use cases are divided into two processing methods.


Before sending SMS verification code, let’s introduce the processing rules of SMS verification code. After we send SMS successfully, we store the verification code in the system cache. Generally, the system cache is stored in redis. The cache needs a key and a defined class object for storage.

We can define the stored object class and use it in the system.

    ///SMS login dynamic password cache object
    public class SmsLoginCodeCacheItem
        public const string CacheName = "AppSmsLoginCodeCacheItem";

        public string Code { get; set; }

        public string PhoneNumber { get; set; }

        public SmsLoginCodeCacheItem()

        public SmsLoginCodeCacheItem(string code, string phone)
            Code = code;
            PhoneNumber = phone;

When the system module is initialized, we can configure the corresponding expiration time of the cache, as shown below.

//Configure SMS login dynamic code expiration date
            Configuration.Caching.Configure(SmsLoginCodeCacheItem.CacheName, cache =>
                cache.DefaultSlidingExpireTime = TimeSpan.FromMinutes(Constants.SmsCodeExpiredMinutes);

Send SMS verification code as the logic code of dynamic password, as shown below.

        ///Send login dynamic code
        ///Mobile login dynamic code
        public async Task SendPhoneLoginSmsCode([FromBody] AuthenticateByPhoneCaptchaModel model)
            //Obtain random 6-bit digital dynamic verification code
            var code = RandomHelper.GetRandom(100000, 999999).ToString();

            //Use custom template to process SMS sending
            string message = string.Format(Constants.MySmsCodeTemplate, code);
            var result =  await _smsSender.SendAsync(model.PhoneNumber, message);
                var cacheKey = model.PhoneNumber;// Store verification code cache with mobile phone number as key
                var cacheItem = new SmsLoginCodeCacheItem { Code = code, PhoneNumber = model.PhoneNumber };

                var cache = _cacheManager.GetCache(SmsLoginCodeCacheItem.CacheName);
                cache.Set(cacheKey, cacheItem);

            return result;

We also need to design a dynamic SMS login interface in the front end, as shown below.

After the SMS is sent successfully, you can view the corresponding dynamic code on the user’s mobile phone.

After sending the verification code, we can also see the corresponding data in redis, as shown below.


2. Dynamic code login processing

After sending the SMS code, the system will store the data in the cache for a period of time. If you log in during this period, you will match according to the cache. If the matching is successful, you can process the relevant login identity.

The processing code of system login verification is as follows.

        ///Authorization through mobile phone verification code
        ///Mobile phone verification code dto
        public async Task AuthenticateByPhoneCaptcha([FromBody] AuthenticateByPhoneCaptchaModel model)
            var loginResult = await GetLoginResultByPhoneCaptchaAsync(

            //if(loginResult.Result == AbpLoginResultType.Success)
            //Here, the SMS cache is successfully removed
            var cache = _cacheManager.GetCache(SmsLoginCodeCacheItem.CacheName);
            cache.Remove(model.PhoneNumber);// Remove cached SMS key value

            var accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity));
            return new AuthenticateResultModel
                AccessToken = accessToken,
                ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds,
                EncryptedAccessToken = GetEncryptedAccessToken(accessToken),
                UserId = loginResult.User.Id

The main logic here is encapsulated in   In getloginresultbyphone captchaasync, the login method can be changed by referring to the basic login method of ABP framework.

        ///Get the login result and pass the mobile phone verification code
        ///Mobile phone number
        ///Verification code
        ///Tenant name
        private async Task> GetLoginResultByPhoneCaptchaAsync(string phoneNumber, string captcha, string tenancyName)
            var loginResult = await _logInManager.LoginByMobileAsync(phoneNumber, captcha, tenancyName);
            switch (loginResult.Result)
                case AbpLoginResultType.Success:
                    return loginResult;
                    throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(loginResult.Result, loginResult.User.UserName, tenancyName);

Referring to the login authorization method based on ABP framework, we add a similar authentication code login management method in usermanager, as shown below.

The front end handles the operations of sending verification code and login authorization. It is a call to the API, so it needs to encapsulate the corresponding API processing.


Then, following the routine login processing, write a dynamic code login processing method and put it in the corresponding module.

Dynamiclogin ({commit}, userinfo) {// log in with dynamic password
    const { mobile, smscode } = userInfo
    return new Promise((resolve, reject) => {
      tokenauth.AuthenticateByPhoneCaptcha({ phoneNumber: mobile.trim(), smsCode: smscode }).then(response => {
        Const {result} = response // get the result of the returned object
        //Console.log (result) // record data
        Var token = result.accesstoken // user token
        Var userid = result.userid // user ID

        //Modify the state object and record the token and user ID
        commit('SET_TOKEN', token)
        commit('SET_USERID', userId)
        //Store cookies

      }).catch(error => {


In the login interface, enter the dynamic code to log in and successfully enter the system, which is the same as the conventional processing.


The above is to build a dynamic code login process by referring to the conventional account and password login method. The process is similar, but it integrates several processes such as SMS sending, cache processing and account login, which can be used as a simple system login process.