Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the login function of SMS CAPTCHA by java

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you how to achieve java SMS CAPTCHA login function, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Business case

As shown below, it is a well-known entry to log in by SMS.

After entering the mobile phone number, the following effect occurs

After entering the verification code received on the phone, you can log in normally.

Analysis of business key points

The above is a normal business process for logging in using SMS verification code. In actual development, there are more factors to consider, such as:

What is the number of bits of the verification code?

How to store CAPTCHA

How to prevent text messages from being brushed

Countdown function, how to cooperate with the front and rear ends

In fact, the function of SMS verification code is not difficult, and it is rare to consider how to achieve comprehensive coverage of business scenarios and functional details.

Thoughts on the realization of SMS CAPTCHA function

Editor combined with practical experience and research, at present, the more popular approach is to use redis as SMS verification code, presumably at this point, students who know the business should have guessed

The complete business logic is roughly as follows:

According to the implementation idea of this business logic, we can roughly sort out the writing logic of the code. in the process of editor development, we have encountered a bit of difficulty, that is, the validity period of CAPTCHA. We mainly consider the following two points:

The validity period of the verification code stored at the backend

The relationship between front-end page countdown and back-end validity period

The issue of validity period

Let's write code to demonstrate the complete process.

Pre-preparation: build a springboot project

Operation steps

1. Import core dependencies

Org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-starter-web 2.2.1.RELEASE

2. The method of compiling and obtaining SMS verification code

@ Servicepublic class SmsServiceImpl implements SmsService {public static final String VERIFY_CODE = "login:verify_code:"; @ Autowired private DbUserMapper dbUserMapper; @ Autowired private RedisTemplate redisTemplate; @ Override public String getSmsVerifyCode (String phone) {if (StringUtils.isEmpty (phone)) {throw new RuntimeException ("user's mobile number is empty");} QueryWrapper queryWrapper = new QueryWrapper (); queryWrapper.eq ("mobile", phone) DbUser dbUser = dbUserMapper.selectOne (queryWrapper); if (dbUser = = null) {throw new RuntimeException ("user does not exist");} String smsVerifyCode = getSmsVerifyCode (); String smsCodeKey = VERIFY_CODE + dbUser.getUserId (); String existedSmsCode = redisTemplate.opsForValue (). Get (smsCodeKey) / / if the CAPTCHA already exists, if (StringUtils.isNotEmpty (existedSmsCode)) {Long expireTime = redisTemplate.opsForValue (). GetOperations () .getExpire (smsCodeKey); long lastTime = 60 * 3-expireTime / / the verification code is valid within 3 minutes. Between 1 minute and 3 minutes, the user can continue to enter the verification code or re-obtain the verification code. The new verification code will overwrite the old if (lastTime > 60 & & expireTime > 0) {/ / call the third-party platform to send text messages, and only the SMS messages have been sent successfully. To save the SMS verification code to redis System.out.println ("SMS sending logic is called here") RedisTemplate.opsForValue () .set (smsCodeKey, smsVerifyCode, 60 * 3, TimeUnit.SECONDS); System.out.println ("SMS verification code: + smsVerifyCode);} / / do not obtain the verification code if (lastTime < 60) {throw new RuntimeException (" click send again in one minute ") }} else {/ / calls the notify service to send SMS messages. Only if the SMS message of notify is sent successfully, the SMS verification code can be saved to redis System.out.println ("SMS sending logic is called here."); System.out.println ("SMS verification code:" + smsVerifyCode) RedisTemplate.opsForValue () .set (smsCodeKey, smsVerifyCode, 60 * 3, TimeUnit.SECONDS);} return smsVerifyCode;} / * * randomly acquire 6-digit SMS digital verification code * * @ return * / public static String getSmsVerifyCode () {Random random = new Random (); String code = "; for (int I = 0; I < 6) Code +) {int rand = random.nextInt (10); code + = rand;} return code;}}

Several scenarios need to be fully considered when sending SMS verification codes:

Enter the mobile phone number for the first time, and when you get the verification code, the validity period of the verification code set at the backend is 3 minutes, and the countdown to the front end is 1 minute.

Within 1 minute, the user cannot obtain the verification code for the second time. After 1 minute, the user can get the verification code again.

After more than 1 minute, when the same user clicks to get the verification code again, the backend needs to actively remove the last verification code stored by redis.

Within the validity period of 3 minutes, users can enter the verification code for the first time to log in at any time.

After the login is successful, the login API needs to actively remove the verification code in the redis.

The above is the core business method of CAPTCHA. Let's write a login method. When the basic CAPTCHA and CAPTCHA are passed, you can log in.

@ Override public String login (String userId, String smsCode) {if (StringUtils.isEmpty (userId)) {throw new RuntimeException ("user ID required");} if (StringUtils.isEmpty (smsCode)) {throw new RuntimeException ("CAPTCHA cannot be empty");} QueryWrapper queryWrapper = new QueryWrapper (); queryWrapper.eq ("user_id", userId) DbUser dbUser = dbUserMapper.selectOne (queryWrapper); if (dbUser = = null) {throw new RuntimeException ("user does not exist");} / / verification code String smsCodeKey = VERIFY_CODE + dbUser.getUserId (); String verifyCode = redisTemplate.opsForValue () .get (smsCodeKey) If (StringUtils.isEmpty (verifyCode)) {throw new RuntimeException ("SMS verification code does not exist or has expired");} if (! StringUtils.equals (smsCode, verifyCode)) {throw new RuntimeException ("SMS verification code error") } / / TODO other login business logic to be verified System.out.println ("perform other businesses."); System.out.println ("login success"); / / finally clean up the verification code if (redisTemplate.hasKey (smsCodeKey)) {redisTemplate.delete (smsCodeKey);} return "login success";}

3. Provide access to CAPTCHA and login interface

@ RestControllerpublic class SmsController {@ Autowired private SmsService smsService; @ GetMapping ("get/sms_code") public String getSmsVerifyCode (@ RequestParam ("phone") String phone) {return smsService.getSmsVerifyCode (phone) Log in to * @ param userId * @ param smsCode * @ return * / @ GetMapping ("/ login") public String login (@ RequestParam ("userId") String userId,@RequestParam ("smsCode") String smsCode) {return smsService.login (userId,smsCode);}}

Start the redis service, start the project, and the database prepares a piece of data in advance.

Scenario test 1: get the CAPTCHA

Call the login API and use the verification code above:

The scene test obtains the CAPTCHA several times in 2:1 minutes.

Get the CAPTCHA for the first time

Get the CAPTCHA again

In more than 1 minute and less than 3 minutes, get the CAPTCHA again and get the new CAPTCHA. At the same time, the latest CAPTCHA is stored in redis.

Scenario Test 3: login input error CAPTCHA

Generally speaking, the function of using redis to implement SMS CAPTCHA login is not too complicated, mainly because it needs to take full account of their respective usage scenarios.

The above is all the contents of the article "how to achieve SMS CAPTCHA login function in java". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report