移动端应用----手机验证码登录

一、短信发送

  目前市面上有很多第三方提供的短信服务,这些第三方短信服务会和各个运营商(移动、联通、电信)对接,我们只需要注册成为会员并且按照提供的开发文档进行调用就可以发送短信。需要说明的是,这些短信服务一般都是收费服务。

  常用短信服务:阿里云、华为云、腾讯云、京东、梦网、乐信

  阿里云短信服务介绍:阿里云短信服务(Short Message Service)是广大企业客户快速触达手机用户所优选使用的通信能力。调用API或用群发助手,即可发送验证码、通知类和营销类短信;国内验证短信秒级触达,到达率可达99%;国际/港澳台短信覆盖200多个国家和地区、安全稳定,广受出海企业选用。

  应用场景:验证码、短信通知、推广短信

  阿里云官网:https://www.aliyun.com/

  具体开发步骤:

  1、导入Maven坐标

复制代码
 <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、调用API

  

二、手机验证码登录

需求分析:

  为了方便用户登录,移动端通常都会提供通过手机验证码登录的功能

  优点:方便快捷,无需注册,直接登录。使用短信验证码作为登录凭证,无需记忆密码。安全

登录流程:输入手机号-》获取验证码-》输入验证码-》点击登录-》登录成功

注意:通过手机验证码登录,手机号是区分不同用户的标识。

数据模型:通过手机验证码登录时,涉及的表为user表,即用户表。

代码梳理交互过程:

1、在登录页面输入手机号,点击【获取验证码】按钮,页面发送ajax请求,在服务端调用短信服务API给指定手机号发送验证短信

2、在登录页面输入验证码,点击【登录】按钮,发送ajax请求,在服务端处理登录请求

代码开发:

(1)修改LoginCheckFilter,此过滤器用于检查用户的登录状态,我们在进行手机验证码登录时,发送的请求需要在此过滤器处理时直接放行

复制代码
  //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",//移动端发送短信
                "/user/login"//移动端登录
        };
复制代码
复制代码
  //4-2、判断移动端登录状态,如果已登录,则直接放行
        if(request.getSession().getAttribute("user")!=null){
            log.info("移动端用户已登录,用户为:{}", request.getSession().getAttribute("user"));

            long userId = (long)request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request, response);

            return;
        }
复制代码
复制代码
package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 发送手机短信验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        System.out.println(phone);
        if(phone!=null){
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code:{}", code);
            //调用阿里云提供的短信服务API完成发送短信
            //SMSUtils.sendMessage("瑞吉外卖", "", phone, code);

            //需要将生成的验证码保存到Session
            session.setAttribute(phone, code);
            return R.success("手机验证码短信发送成功");
        }
        return R.error("手机验证码短信发送失败");

    }

    /**
     * 移动端用户登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map user, HttpSession session){
        log.info(user.toString());
        //获取手机号
        String phone = user.get("phone").toString();
        //获取验证码
        String  code = user.get("code").toString();
        //进行验证码比对(页面提交的验证码和Session中保存的验证码)
        Object codeInSession = session.getAttribute(phone);
        if(codeInSession!=null && codeInSession.equals(code)){
            //如果能够比对成功,说明登录成功
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User person = userService.getOne(queryWrapper);
            if(person==null){
                // 判断当前手机号对应的用户是否为新用户,如果是新用户就自动完成注册
                person = new User();
                person.setPhone(phone);
                person.setStatus(1);
                userService.save(person);
            }
            return R.success(person);
        }
        return R.error("短信发送失败");
    }

}
复制代码

 

posted @   佛系粥米  阅读(347)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示