短信验证码登录

  1. 首先去阿里云服务器开通短信服务功能,进入短信服务界面
  2. 点击国内消息,申请一个签名和模板

  3. 申请一个AccessKey,并且将短信服务的权限加入其中
  4. 加入相关的依赖
        <dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-core</artifactId><version>4.4.0</version></dependency><dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-dysmsapi</artifactId><version>1.0.0</version></dependency>
  1. 接下来利用Open API生成使用服务的代码
@Component
public class Message {public static void messagePost(String mobile, String message){DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "******************", "******************");IAcsClient client = new DefaultAcsClient(profile);CommonRequest request = new CommonRequest();request.setSysMethod(MethodType.POST);request.setSysDomain("dysmsapi.aliyuncs.com");request.setSysVersion("2017-05-25");request.setSysAction("SendSms");request.putQueryParameter("RegionId", "cn-hangzhou");request.putQueryParameter("PhoneNumbers",mobile);request.putQueryParameter("SignName", "校园帮手");request.putQueryParameter("TemplateCode", "SMS_191485017");request.putQueryParameter("TemplateParam", "{\"code\":"+message+"}");try {CommonResponse response = client.getCommonResponse(request);System.out.println(response.getData());} catch (ServerException e) {e.printStackTrace();} catch (ClientException e) {e.printStackTrace();}}
}
  1. 接下来实现生成验证码,并将生成的验证码存入缓存中,并且调用Message类发送短信。
    public Result<Boolean> authcode_get(LoginVo loginVo) {String mobile=loginVo.getMobile();String password = "1" + RandomStringUtils.randomNumeric(5);//生成随机数,我发现生成5位随机数时,如果开头为0,发送的短信只有4位,这里开头加个1,保证短信的正确性redisService.set(UserKey.getBymobile,mobile, password);//将验证码存入缓存Message.messagePost(mobile, password);//发送短息return Result.success(true);}

接下来获取前端传来的手机号以及输入的验证码,并与存入缓存中的验证码做校验,登录。

    public Result<Boolean>  authcode_login(LoginVo loginVo) {String mobile=loginVo.getMobile();String password=loginVo.getPassword();String s1=redisService.get(UserKey.getBymobile,mobile,String.class);System.out.println(s1);if (s1.equals(password)) {return Result.success(true);} else {return Result.error(CodeMsg.PASSWORD_ERROR);}

实现效果图
总登录界面

验证码登录界面(验证码错误)
验证码做正确

第三方登录
首先申请一个QQ互联的权限
网址:https://connect.qq.com/manage.html

  1. 加入相关的依赖
        <dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-redis</artifactId><version>2.2.5.RELEASE</version></dependency><!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><version>2.2.5.RELEASE</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.2</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-io</artifactId><version>1.3.2</version></dependency>
  1. 写配置文件
constants.qqAppId=101513767
constants.qqAppSecret=b1d978cefcf405388893d8e686d307b0
constants.qqRedirectUrl=http://127.0.0.1:8080/QQLogin
  1. 获取QQ信息的pojo类
    private Integer ret;private String msg;private Integer is_lost;private String nickname;private String gender;private String province;private String city;private String year;private String constellation;private String figureurl;private String figureurl_1;private String figureurl_2;private String figureurl_qq;private String figureurl_qq_1;private String figureurl_qq_2;private String is_yellow_vip;private String vip;private String yellow_vip_level;private String level;private String is_yellow_year_vip;
  1. http工具类 HttpClientUtils

  2. qq登录的Controller类

package com.miaoshaw.miaoshawdemo.controller;import com.alibaba.fastjson.JSON;
import com.miaoshaw.miaoshawdemo.Util.HttpClientUtils;
import com.miaoshaw.miaoshawdemo.Util.URLEncodeUtil;
import com.miaoshaw.miaoshawdemo.qq.Constants;
import com.miaoshaw.miaoshawdemo.qq.QQUserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;@Controller
public class QQController {/*** QQ :读取Appid相关配置信息静态类*/@Autowiredprivate Constants constants;/*** 登录页*/@GetMapping("/")public String login() {return "login";}/*** 获得跳转到qq登录页的url,前台直接a连接访问** @author wangsong* @date 2019年6月18日 下午8:29:20* @param session* @return* @throws Exception*/@GetMapping("/getQQCode")public String getCode(HttpSession session, Model model) throws Exception {// 拼接urlStringBuilder url = new StringBuilder();url.append("https://graph.qq.com/oauth2.0/authorize?");url.append("response_type=code");url.append("&client_id=" + constants.getQqAppId());// 回调地址 ,回调地址要进行Encode转码String redirect_uri = constants.getQqRedirectUrl();// 转码url.append("&redirect_uri=" + URLEncodeUtil.getURLEncoderString(redirect_uri));url.append("&state=ok");// HttpClientUtils.get(url.toString(), "UTF-8");System.out.println(url.toString());model.addAttribute("url", url);return "login";}/*** 开始登录** @param code* @param* @param 实际业务:token过期调用刷新    token重新获取token信息* @param 数据库字段: accessToken,expiresIn,refreshToken,openId* @return* @throws Exception*/@GetMapping("/QQLogin")@ResponseBodypublic QQUserInfo QQLogin(String code, Model model) throws Exception {if (code != null) {System.out.println(code);}//获取tocketMap<String, Object> qqProperties = getToken(code);//获取openId(每个用户的openId都是唯一不变的)String openId = getOpenId(qqProperties);qqProperties.put("openId",openId);//tocket过期刷新token//Map<String, Object> refreshToken = refreshToken(qqProperties);//获取数据QQUserInfo  userInfo =  getUserInfo(qqProperties);return userInfo;}/*** 获得token信息(授权,每个用户的都不一致) --> 获得token信息该步骤返回的token期限为一个月** @param (保存到Map<String,String> qqProperties)* @author wangsong* @return* @throws Exception* @date 2019年6月18日 下午8:56:45*/public Map<String, Object> getToken(String code) throws Exception {StringBuilder url = new StringBuilder();url.append("https://graph.qq.com/oauth2.0/token?");url.append("grant_type=authorization_code");url.append("&client_id=" + constants.getQqAppId());url.append("&client_secret=" + constants.getQqAppSecret());url.append("&code=" + code);// 回调地址String redirect_uri = constants.getQqRedirectUrl();// 转码url.append("&redirect_uri=" + URLEncodeUtil.getURLEncoderString(redirect_uri));// 获得tokenString result = HttpClientUtils.get(url.toString(), "UTF-8");System.out.println("url:" + url.toString());// 把token保存String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(result, "&");String accessToken = StringUtils.substringAfterLast(items[0], "=");Long expiresIn = new Long(StringUtils.substringAfterLast(items[1], "="));String refreshToken = StringUtils.substringAfterLast(items[2], "=");//token信息Map<String,Object > qqProperties = new HashMap<String,Object >();qqProperties.put("accessToken", accessToken);qqProperties.put("expiresIn", String.valueOf(expiresIn));qqProperties.put("refreshToken", refreshToken);return qqProperties;}/*** 刷新token 信息(token过期,重新授权)** @return* @throws Exception*/@GetMapping("/refreshToken")public Map<String,Object> refreshToken(Map<String,Object> qqProperties) throws Exception {// 获取refreshTokenString refreshToken = (String) qqProperties.get("refreshToken");StringBuilder url = new StringBuilder("https://graph.qq.com/oauth2.0/token?");url.append("grant_type=refresh_token");url.append("&client_id=" + constants.getQqAppId());url.append("&client_secret=" + constants.getQqAppSecret());url.append("&refresh_token=" + refreshToken);System.out.println("url:" + url.toString());String result = HttpClientUtils.get(url.toString(), "UTF-8");// 把新获取的token存到map中String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(result, "&");String accessToken = StringUtils.substringAfterLast(items[0], "=");Long expiresIn = new Long(StringUtils.substringAfterLast(items[1], "="));String newRefreshToken = StringUtils.substringAfterLast(items[2], "=");//重置信息qqProperties.put("accessToken", accessToken);qqProperties.put("expiresIn", String.valueOf(expiresIn));qqProperties.put("refreshToken", newRefreshToken);return qqProperties;}/*** 获取用户openId(根据token)** @param 把openId存到map中* @return* @throws Exception*/public String getOpenId(Map<String,Object> qqProperties) throws Exception {// 获取保存的用户的tokenString accessToken = (String) qqProperties.get("accessToken");if (!StringUtils.isNotEmpty(accessToken)) {// return "未授权";}StringBuilder url = new StringBuilder("https://graph.qq.com/oauth2.0/me?");url.append("access_token=" + accessToken);String result = HttpClientUtils.get(url.toString(), "UTF-8");String openId = StringUtils.substringBetween(result, "\"openid\":\"", "\"}");return openId;}/*** 根据token,openId获取用户信息*/public QQUserInfo getUserInfo(Map<String,Object> qqProperties) throws Exception {// 取tokenString accessToken = (String) qqProperties.get("accessToken");String openId = (String) qqProperties.get("openId");if (!StringUtils.isNotEmpty(accessToken) || !StringUtils.isNotEmpty(openId)) {return null;}//拼接urlStringBuilder url = new StringBuilder("https://graph.qq.com/user/get_user_info?");url.append("access_token=" + accessToken);url.append("&oauth_consumer_key=" + constants.getQqAppId());url.append("&openid=" + openId);// 获取qq相关数据String result = HttpClientUtils.get(url.toString(), "UTF-8");Object json = JSON.parseObject(result, QQUserInfo.class);QQUserInfo userInfo = (QQUserInfo) json;return userInfo;}
}

实现效果图

短信验证码登录,以及第三方登录相关推荐

  1. 防止刷单杜绝薅羊毛:语音验证码和短信验证码及最新一键登录(秒验点验)解决思路

    1.传统的网站和APP在早期开发时很少关注到刷单防范和羊毛党问题.甚至很多网站注册没有考虑到手机绑定.在以PC为主的互联网时代网站注册时很少使用到短信验证码,随着工信部强制要求手机号必须实名认证,同时 ...

  2. python发短信验证码_python利用第三方模块,发送短信验证码

    对于初学者,如何利用第三方python开发包发送短信验证码,下面是具体的实现和记录过程! 环境:虚拟机上centos7平台,python3.7版本: 首先,申请账号的部分就省略了 1. 获得appid ...

  3. 手机短信验证码一次性 需要第三方平台

    用户登录到页面 - 输入手机号- 点击获取验证码按钮-后台生成6位随机数 - 通过第三方平台发送到手机 - 并把随机验证码放到session - 用户输入验证码 - 后台匹配手机号与验证码 - 120 ...

  4. 手把手带你在集成SpringSecurity的SpringBoot应用中添加短信验证码登录认证功能

    本文目录 前言 1 自定义AuthenticationToken类 2 自定义AuthenticationProvider类 3 自定义MobilePhoneAuthenticationFilter ...

  5. JS实现注册登录发送短信验证码动态显示60S倒计时完整案例

    通常在web项目中都会遇到账户注册或者忘记密码时需要发送短信验证码的功能,虽然说这种功能很常见,但是实际开发过程中很多人还会遇到不少坑.笔者经过整理把最近项目中的用到的这个发送短信验证码动态显示60S ...

  6. 手机老是收不到短信验证码?我来告诉你为什么!

    有些用户在使用某产品时可能会出现短信验证码收不到的情况,同事之前也遇到过这样的情况,连续发送多次依然收不到短信.那么短信验证码为什么会发送失败.原因有哪些呢.#短信验证码安全 现在短信验证码服务在各种 ...

  7. 短信验证码总是发送失败是什么原因?

    有些用户在使用某产品时可能会出现短信验证码收不到的情况,同事之前也遇到过这样的情况,连续发送多次依然收不到短信.那么短信验证码为什么会发送失败.原因有哪些呢.#短信验证码安全 现在短信验证码服务在各种 ...

  8. python读取短信验证码_我用Python给你发了个短信验证码,你也来试试

    点击上方毛利学python,选择置顶或星标 第一时间送达Python 技术干货! 在互联网时代,为了保证操作的安全性,我们几乎所有的登录.注册等操作都需要用到短信验证码,一是为了防止自己的平台被机器频 ...

  9. 程序君带你畅聊发送短信验证码

    现在不管是网站,还是app等互联网和移动互联网产品,绝大部分注册都是直接用手机号注册登录的,方式就是给手机发送短信验证码,然后把验证码填入,后台程序去匹配判断用户填入的验证码和发送的是否一致. 我最近 ...

  10. JAVA外卖项目第五天 套餐模块和短信验证码

    瑞吉外卖-第五天 课程内容 新增套餐 套餐分页查询 删除套餐 短信发送 手机验证码登录 1. 新增套餐 1.1 需求分析 套餐就是菜品的集合. 后台系统中可以管理套餐信息,通过新增套餐功能来添加一个新 ...

最新文章

  1. 利用python来解析html
  2. Java线程:创建与启动
  3. andriod之应用内置浏览器 webview
  4. java 程序执行原理
  5. 雷蛇在天猫618大爆发,雷军第二天就找其创始人取经
  6. springboot集成kafka_厉害!腾讯T3-2都还在学的微服务+MySQL+Kafka+boot2.x+虚拟机PDF
  7. 企业计算机仿真技术应用,基于计算机仿真技术的企业生产物流系统优化研究
  8. 刺激战场微信登录更换服务器,刺激战场怎么换微信号登陆 切换微信账号登陆方法...
  9. latex学习3:教你如何在word中像LaTex那样打公式
  10. 酷睿i7 1165g7相当于什么水平 i71165g7属于哪个档次
  11. pm2启动node项目
  12. 云计算导论(第二版)李伯虎著全部课后题的答案
  13. 电脑卡顿,终于解决了多年的电脑卡顿问题
  14. 网站需要服务器密码登录密码忘记了怎么办,云服务器登录需要密码忘记了怎么办...
  15. LINUX学习网址精选
  16. SpringBoot根据模板生成Word文件,然后Word转PDF
  17. ubuntu1604安装sougou输入法
  18. Linux-简易使用
  19. ESP32 串口升级
  20. 中国全国地区MYSQL 地区SQL数据表(省,市,区,县)

热门文章

  1. 史上最强红利指数——标普A股红利机会指数全解析
  2. 乐优商城之项目搭建(四)
  3. 超宽带室内信道模型研究与matlab仿真,复杂室内环境超宽带信号信道模型及仿真结果分析.pdf...
  4. ElasticSearch 7.x新特性体验-安装部署
  5. Selenium: either the element is no longer attached to the DOM, it is not in the curren
  6. html5网站上线模版,HTML5网站即将上线前端模板
  7. java:多态详解,以及对象的向上和向下转型
  8. windows, pip install xgboost 出现错误:No files/directories in ******
  9. 【帆软报表】报表类型简介
  10. ubuntu20.04 server 无图形命令行安装