当前位置:网站首页>[Ruiji takeout project] Day5 - Chapter 6 mobile verification code login
[Ruiji takeout project] Day5 - Chapter 6 mobile verification code login
2022-07-28 22:20:00 【ajjjjjjjjjtty】
This chapter introduces the mobile authentication code login
- Click to get the verification code
- Received text messages , And enter the verification code
- Click login , Login successful
Text messaging _ Introduction to SMS service and Alibaba cloud SMS service
Introduction to SMS service
- At present, there are many SMS services provided by third parties on the market , These third-party SMS services will work with various operators ( Move 、 Unicom 、 telecom ) docking
- We only need to register as a member and call according to the development documents provided to send text messages
-* It should be noted that *, These SMS services are generally paid services
Common SMS service :
- Alibaba cloud
- Hua Wei Yun
- Tencent cloud
- JD.COM
- monternet
- Music letter
Used in this project : Alibaba cloud SMS service (Short Message Service) It is the preferred communication capability for enterprise customers to quickly reach mobile phone users . call API Or use a group assistant , You can send the verification code 、 Notification and marketing SMS ; Domestic verification SMS second touch , The highest arrival rate can reach 99%; The international / SMS coverage in Hong Kong, Macao and Taiwan 200 Multiple countries and regions , Safe and stable , Widely used by sea enterprises .
Application scenarios :
- Verification Code
- SMS notification
- Promote SMS
Introduction to Alibaba cloud SMS service
Open the browser , Log in to alicloud — website :https://cn.aliyun.com/
Click on product , Enter the SMS service in the search box , And click search
Alibaba cloud SMS service steps :
First step : Registered account
The second step : Sign in
The third step : Alibaba cloud SMS service
Text messaging _ Alibaba cloud SMS service
Set SMS signature
After opening SMS service , Enter the SMS service management page , Select the domestic message menu , We need to add SMS signature here
SMS signature indicates the identity of the sender
What is SMS signature ?
- SMS signature is the signature of the sender , Indicates the identity of the sender
- We need to call Alibaba cloud SMS service to send SMS , Signature is an essential part
Add SMS signature method
Be careful : It is difficult for individuals to apply for signature , So we just need to know the specific process of using SMS signature
Set SMS template
Switch to 【 Template Management 】 TAB :
The SMS template contains the SMS sending content 、 scene 、 Variable information
Each set template has a message template details , The template details contain the template 6 Bar information

Add the template , And it is approved after submission
A series of steps , Omit directly
Text messaging _ Code development _ Refer to the official document to package the SMS tool class
Refer to official documents
Use Alibaba cloud SMS service to send text messages , You can refer to the official documents .
Specific development steps :
- Import maven coordinate
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.5.16</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>2.1.0</version>
</dependency>
2. stay reggie Package under the new utils package , Import the tool class
package com.itzq.reggie.utils;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
/**
* SMS sending tools
*/
public class SMSUtils {
/**
* Send a text message
* @param signName Signature
* @param templateCode Templates
* @param phoneNumbers cell-phone number
* @param param Parameters
*/
public static void sendMessage(String signName, String templateCode,String phoneNumbers,String param){
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "", "");
IAcsClient client = new DefaultAcsClient(profile);
SendSmsRequest request = new SendSmsRequest();
request.setSysRegionId("cn-hangzhou");
request.setPhoneNumbers(phoneNumbers);
request.setSignName(signName);
request.setTemplateCode(templateCode);
request.setTemplateParam("{\"code\":\""+param+"\"}");
try {
SendSmsResponse response = client.getAcsResponse(request);
System.out.println(" Message sent successfully ");
}catch (ClientException e) {
e.printStackTrace();
}
}
}
Check the SMS product documentation java SDK, Learn about SMS services java SDK Usage and examples of
Mobile verification code login business development
- Demand analysis
- Data model
- Code development
- A functional test
Mobile phone verification code login _ Demand analysis _ Data model
Demand analysis
To make it easier for users to log in , The mobile terminal usually provides the login code
Advantages of mobile verification code login :
- Convenient and quick , Without registration , Direct login
- Use SMS verification code as login voucher , No need to remember the password
- Security
The login process :
- Enter phone number > Get verification code > Enter verification code > Click login > Login successful
Be careful : Login through mobile verification code , Mobile phone number is the identification to distinguish different users
User login interface
Data model
When logging in through mobile verification code , The tables involved are user surface , I.e. user table . The structure is as follows :

Be careful :
- Mobile phone number is the identification to distinguish different users , Judge whether the entered mobile phone number is stored in the table when the user logs in
- If it's not in the table , It indicates that the user is a new user , Automatically save the user in user In the table
Mobile phone verification code login _ Code development _ Sort out the interaction process & modify LoginCheckFilter
Sort out the interaction process
Before developing code , You need to sort out the interaction process between the front-end page and the server when logging in :
- On the login page (front/page/login.html) Enter phone number , Click on 【 Get verification code 】 Button , Page sending ajax request , On the server Call SMS service API Send verification code SMS to the specified mobile phone number
- Enter the verification code on the login page , Click on 【 Sign in 】 Button , send out ajax request , Handle the login request on the server
Develop mobile phone verification code login function , In fact, it is to write code on the server side to process the information sent by the front-end page 2 One request is enough .
Code development - preparation
Before developing business functions , First, create the basic structure of classes and interfaces that need to be used :
- Entity class user ( Import directly from the course materials )
- Mapper Interface UserMapper
- Business layer interface UserService
- Business layer implementation classes UserServicelmpl
- Control layer UserController
- Tool class SMSutils、ValidateCodeutils( Import directly from the course materials )
stay LoginCheckFilter Add code under class , Determine whether the user is logged in
//4-2 Determine login status , If you are logged in , Then direct release
if(request.getSession().getAttribute("user") != null){
log.info(" User logged in , user id by :{}",request.getSession().getAttribute("user"));
Long userId = (Long)request.getSession().getAttribute("user");
BaseContext.setCurrentId(userId);
filterChain.doFilter(request,response);
return;
Mobile phone verification code login _ Code development _ Send verification code message
Code development
Be careful
- To send a short message, you only need to call the methods in the encapsulated tool class
- Use your mobile number to log in, and the process runs smoothly , In the test, we don't really send text messages , Just put the verification code information , Log output
- Login time , We can see the generated verification code directly from the console ( In fact, it is the verification code sent to our mobile phone )
stay UserController In the control layer , add to sendMsg Method
@PostMapping("/sendMsg")
public R<String> sendMsg(@RequestBody User user, HttpSession session){
// Get cell phone number
String phone = user.getPhone();
if (StringUtils.isNotEmpty(phone)){
// Generate random 4 Bit verification code
String code = ValidateCodeUtils.generateValidateCode4String(4);
log.info("code={}",code);
// Call the SMS service provided by Alibaba cloud API Complete SMS sending
//SMSUtils.sendMessage(" Reggie takeout ","",phone,code);
// You need to save the generated verification code to session
session.setAttribute(phone,code);
return R.success(" Message sent successfully ");
}
return R.error(" SMS sending failed ");
}
stay UserController In the control layer class , add to login Method , Test whether the server can accept the data submitted by the front end
@PostMapping("/login")
public R<String> login(@RequestBody Map map, HttpSession session){
log.info(map.toString());
return R.error(" SMS sending failed ");
}
Improve user login code
@PostMapping("/login")
public R<User> login(@RequestBody Map map, HttpSession session){
log.info(map.toString());
// Get cell phone number
String phone = map.get("phone").toString();
// Get verification code
String code = map.get("code").toString();
// from session Get the saved verification code from
String codeInSession = session.getAttribute(phone).toString();
// Compare the verification code ( Verification code and... Submitted by the page session The verification code stored in )
if (code != null && code.equals(codeInSession)){
// If the comparison is successful , Login succeeded
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::getPhone,phone);
User user = userService.getOne(queryWrapper);
if (user == null){
// Judge whether the current mobile phone number is a new user , If it is a new user, the injection is automatically completed
user = new User();
user.setPhone(phone);
userService.save(user);
}
return R.success(user);
}
return R.error(" Login failed ");
}
Restart project , Enter the mobile number on the user login page , And the obtained verification code , Click login
The page successfully jumps to the service user interface
user The tested mobile phone number was successfully added to the table ( Unregistered mobile number )
边栏推荐
猜你喜欢

Jmeter 安装第三方插件 Plugins Manager

Part 8: creating camera classes

Basic introduction of Rockwell AB PLC rslogix digital quantity IO module

拥抱开源指南

Kubeedge releases white paper on cloud native edge computing threat model and security protection technology

In Kingbase, the user is specified to search the schema by default, or the user cannot use the function under the public schema

【机器学习】朴素贝叶斯对文本分类--对人名国别分类

2021数学建模B组练习

40. Combined sum II

Bugku,Web:都过滤了
随机推荐
HCIP(8)
阿里云CDN实践
SQL注入 Less42(POST型堆叠注入)
【NLP】生成词云
LCR测试仪最为主要的功能和用途都是什么
Byte side: can TCP and UDP use the same port?
Basic introduction of Rockwell AB PLC rslogix digital quantity IO module
Typeof principle
SQL注入 Less38(堆叠注入)
静态路由和缺省路由实验
SQL injection less38 (Stack Injection)
Win11怎么打开软件通知
迪赛智慧数——折线图(堆叠面积图):2022年不同职业人群存款额占月收入比例排名
2021年数学建模B组代码
MOV格式是不是静态图像文件格式
行内元素和块级元素有什么区别?语义化作用
HCIP(14)
Record the fluent to solve the problem of a renderflex overflowed by 7.3 pixels on the bottom
What is the difference between inline elements and block level elements? Semantic function
Static route and default route experiment