springboot手机短信验证码登录

手机短信验证码登录

    • 方法
    • 总结

方法

*1.获取手机验证码

     /**
     * 获取手机验证码
     */
    @RequestMapping("/getVerificationCode")
    @ResponseBody
    public ResponseData getVerificationCode(UserDto user, HttpServletRequest request, HttpServletResponse response, HttpSession session) {

        if (ToolUtil.isNotEmpty(user.getPhone())) {
            if(ToolUtil.isNotEmpty(session.getAttribute(user.getPhone()))){
                throw new ServiceException(BizExceptionEnum.AUTH_CODE_SENT);
            }
            // 调用短信接口
            String authCode = RandomNumUtils.getRandomNum();
            SMSUtils.sendTextMessage(user.getPhone(),authCode);
            // 存入session
            request.getSession().setAttribute(user.getPhone(),authCode);
            // 过期时间300秒
            request.getSession().setMaxInactiveInterval(300);
        }else {
            throw new ServiceException(BizExceptionEnum.PHONE_NULL);
        }
        return ResponseData.success();
    }

     /**
     * 用户手机登录
     */
    @RequestMapping("/phoneLogin")
    @ResponseBody
    public ResponseData phoneLogin(UserDto user,HttpSession session) {

        if (ToolUtil.isOneEmpty(user.getPhone(), user.getVerificationCode())) {
            throw new ServiceException(BizExceptionEnum.PHONE_CODE_NULL);
        }
        // 账号校验
        User theUser = this.userService.getByPhone(user.getPhone());
        if (theUser == null) {
            throw new ServiceException(BizExceptionEnum.USER_NOT_EXISTED);
        }
        // 校验验证码是否失效
        if(ToolUtil.isEmpty(session.getAttribute(user.getPhone()))){
            throw new ServiceException(BizExceptionEnum.CODE_EXPIRY);
        }
        String authCode = (String) session.getAttribute(user.getPhone());
       if(authCode.equals(user.getVerificationCode())){
           //登录并创建token
           String token = authService.login(theUser.getAccount());
           authService.addLoginCookie(token);
           return  ResponseData.success();
       }else {
           throw new ServiceException(BizExceptionEnum.PHONE_CODE_ERROR);
       }
    }

2.短信发送

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
/**
 * 短信发送工具类
 */
public class SMSUtils {

    /**
     * 访问秘钥
     */
    private static final String ACCESSKEYID = "xxxxxxx";
    private static final String ACCESSKEYSECRET = "xxxxxx";
    /**
     * 模板号
     */
    public static final String VALIDATE_CODE = "xxxxxxx";

    /**
     * 发送短信
     *
     * @param phoneNumbers 手机号码
     * @param authCode     验证码
     */
    public static void sendTextMessage (String phoneNumbers, String authCode) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",ACCESSKEYID,ACCESSKEYSECRET);
        IAcsClient client = new DefaultAcsClient(profile);
        // 组装请求对象
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phoneNumbers);
        // 短信签名名称
        request.putQueryParameter("SignName", "xxxxxx");
        request.putQueryParameter("TemplateCode", VALIDATE_CODE);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + authCode + "\"}" );
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}

3.随机生成验证码

    /**
     * 随机生成六位数验证码
     *
     */
   public class RandomNumUtils {
   
    public static String getRandomNum() {
        Random r = new Random();
        return (r.nextInt(900000) + 100000) + "";
    }
}

总结

前后端分离时,注意跨域导致的sessionID不一致的问题。

你可能感兴趣的:(java)