一、简介

目前我们使用的web系统在登陆功能开发时,不仅仅只是单纯的使用表单填写用户注册信息来进行注册,参考我们现在使用的其他软件存在以下登录情况。

  1. 使用QQ/微信等第三方平台进行授权登录
  2. 使用短信验证码进行登录

常见的就是着两种登录方式,他们使用的频率比单纯的表单填写信息更加的美观。

注意:我们这篇文章只是让我们了解第三方平台账号授权和手机验证码,在此不过多关注和区分登录和注册的逻辑。

二、QQ第三方授权登录

1.获得QQ的权限

进入QQ互联—>点击头像填写个人信息—>应用管理

(审核需要一定的时间)可以参考QQ互联文档资料

2.代码的编写

2.1添加依赖

我们再springboot实现该功能

 <!-- 以下是 qq 登陆需要的相关依赖工具 commons-io, commons-lang3,httpclient,fastjson--><dependency><groupId>org.apache.commons</groupId><artifactId>commons-io</artifactId><version>1.3.2</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.38</version></dependency>

2.2配置文件信息

填写QQ互联的Appid,key,登录后回调地址(必须和QQ互联填写的一致,QQLogin 对应代码里的接口)

constants.qqAppId=101513767
constants.qqAppSecret=b1d978cefcf405388893d8e686d307b0
constants.qqRedirectUrl=http://127.0.0.1:8080/QQLogin

2.3读取配置信息类

@Component
public class Constants {@Value("${constants.qqAppId}")private String qqAppId;@Value("${constants.qqAppSecret}")private String qqAppSecret;@Value("${constants.qqRedirectUrl}")private String qqRedirectUrl;@Value("${constants.weCatAppId}")private String weCatAppId;@Value("${constants.weCatAppSecret}")private String weCatAppSecret;@Value("${constants.weCatRedirectUrl}")private String weCatRedirectUrl;//自行生成set get方法
}

2.4QQ数据实体类

QQ将把返回的信息封装到这里

public class QQUserInfo {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;//自行生成 set get
}

2.5http工具类 HttpClientUtils

public class HttpClientUtils {public static final int connTimeout = 10000;public static final int readTimeout = 10000;public static final String charset = "UTF-8";private static HttpClient client = null;static {PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();cm.setMaxTotal(128);cm.setDefaultMaxPerRoute(128);client = HttpClients.custom().setConnectionManager(cm).build();}public static String postParameters(String url, String parameterStr)throws ConnectTimeoutException, SocketTimeoutException, Exception {return post(url, parameterStr, "application/x-www-form-urlencoded", charset, connTimeout, readTimeout);}public static String postParameters(String url, String parameterStr, String charset, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception {return post(url, parameterStr, "application/x-www-form-urlencoded", charset, connTimeout, readTimeout);}public static String postParameters(String url, Map<String, String> params)throws ConnectTimeoutException, SocketTimeoutException, Exception {return postForm(url, params, null, connTimeout, readTimeout);}public static String postParameters(String url, Map<String, String> params, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception {return postForm(url, params, null, connTimeout, readTimeout);}public static String get(String url) throws Exception {return get(url, charset, null, null);}public static String get(String url, String charset) throws Exception {return get(url, charset, connTimeout, readTimeout);}/*** 发送一个 Post 请求, 使用指定的字符集编码.** @param url* @param body        RequestBody* @param mimeType    例如 application/xml "application/x-www-form-urlencoded"*                    a=1&b=2&c=3* @param charset     编码* @param connTimeout 建立链接超时时间,毫秒.* @param readTimeout 响应超时时间,毫秒.* @return ResponseBody, 使用指定的字符集编码.* @throws ConnectTimeoutException 建立链接超时异常* @throws SocketTimeoutException  响应超时* @throws Exception*/public static String post(String url, String body, String mimeType, String charset, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception {HttpClient client = null;HttpPost post = new HttpPost(url);String result = "";try {if (StringUtils.isNotBlank(body)) {HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset));post.setEntity(entity);}// 设置参数Builder customReqConf = RequestConfig.custom();if (connTimeout != null) {customReqConf.setConnectTimeout(connTimeout);}if (readTimeout != null) {customReqConf.setSocketTimeout(readTimeout);}post.setConfig(customReqConf.build());HttpResponse res;if (url.startsWith("https")) {// 执行 Https 请求.client = createSSLInsecureClient();res = client.execute(post);} else {// 执行 Http 请求.client = HttpClientUtils.client;res = client.execute(post);}result = IOUtils.toString(res.getEntity().getContent(), charset);} finally {post.releaseConnection();if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {((CloseableHttpClient) client).close();}}return result;}/*** 提交form表单** @param url* @param params* @param connTimeout* @param readTimeout* @return* @throws ConnectTimeoutException* @throws SocketTimeoutException* @throws Exception*/public static String postForm(String url, Map<String, String> params, Map<String, String> headers,Integer connTimeout, Integer readTimeout)throws ConnectTimeoutException, SocketTimeoutException, Exception {HttpClient client = null;HttpPost post = new HttpPost(url);try {if (params != null && !params.isEmpty()) {List<NameValuePair> formParams = new ArrayList<org.apache.http.NameValuePair>();Set<Map.Entry<String, String>> entrySet = params.entrySet();for (Map.Entry<String, String> entry : entrySet) {formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));}UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);post.setEntity(entity);}if (headers != null && !headers.isEmpty()) {for (Map.Entry<String, String> entry : headers.entrySet()) {post.addHeader(entry.getKey(), entry.getValue());}}// 设置参数Builder customReqConf = RequestConfig.custom();if (connTimeout != null) {customReqConf.setConnectTimeout(connTimeout);}if (readTimeout != null) {customReqConf.setSocketTimeout(readTimeout);}post.setConfig(customReqConf.build());HttpResponse res = null;if (url.startsWith("https")) {// 执行 Https 请求.client = createSSLInsecureClient();res = client.execute(post);} else {// 执行 Http 请求.client = HttpClientUtils.client;res = client.execute(post);}return IOUtils.toString(res.getEntity().getContent(), "UTF-8");} finally {post.releaseConnection();if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {((CloseableHttpClient) client).close();}}}/*** 发送一个 GET 请求** @param url* @param charset* @param connTimeout 建立链接超时时间,毫秒.* @param readTimeout 响应超时时间,毫秒.* @return* @throws ConnectTimeoutException 建立链接超时* @throws SocketTimeoutException  响应超时* @throws Exception*/public static String get(String url, String charset, Integer connTimeout, Integer readTimeout)throws ConnectTimeoutException, SocketTimeoutException, Exception {HttpClient client = null;HttpGet get = new HttpGet(url);String result = "";try {// 设置参数Builder customReqConf = RequestConfig.custom();if (connTimeout != null) {customReqConf.setConnectTimeout(connTimeout);}if (readTimeout != null) {customReqConf.setSocketTimeout(readTimeout);}get.setConfig(customReqConf.build());HttpResponse res = null;if (url.startsWith("https")) {// 执行 Https 请求.client = createSSLInsecureClient();res = client.execute(get);} else {// 执行 Http 请求.client = HttpClientUtils.client;res = client.execute(get);}result = IOUtils.toString(res.getEntity().getContent(), charset);} finally {get.releaseConnection();if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {((CloseableHttpClient) client).close();}}return result;}/*** 从 response 里获取 charset** @param ressponse* @return*/@SuppressWarnings("unused")private static String getCharsetFromResponse(HttpResponse ressponse) {// Content-Type:text/html; charset=GBKif (ressponse.getEntity() != null && ressponse.getEntity().getContentType() != null&& ressponse.getEntity().getContentType().getValue() != null) {String contentType = ressponse.getEntity().getContentType().getValue();if (contentType.contains("charset=")) {return contentType.substring(contentType.indexOf("charset=") + 8);}}return null;}/*** 创建 SSL连接** @return* @throws GeneralSecurityException*/private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {try {SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {return true;}}).build();SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {@Overridepublic boolean verify(String arg0, SSLSession arg1) {return true;}@Overridepublic void verify(String host, SSLSocket ssl) throws IOException {}@Overridepublic void verify(String host, X509Certificate cert) throws SSLException {}@Overridepublic void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {}});return HttpClients.custom().setSSLSocketFactory(sslsf).build();} catch (GeneralSecurityException e) {throw e;}}public static void main(String[] args) {try {String str = post("https://localhost:443/ssl/test.shtml", "name=12&page=34","application/x-www-form-urlencoded", "UTF-8", 10000, 10000);// String str=// get("https://localhost:443/ssl/test.shtml?name=12&page=34","GBK");/** Map<String,String> map = new HashMap<String,String>(); map.put("name",* "111"); map.put("page", "222"); String str=* postForm("https://localhost:443/ssl/test.shtml",map,null, 10000, 10000);*/System.out.println(str);} catch (ConnectTimeoutException e) {e.printStackTrace();} catch (SocketTimeoutException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}
}

2.6url转码工具类 URLEncodeUtil

不管是以何种方式传递url时,如果要传递的url中包含特殊字符,如想要传递一个+,但是这个+会被url会被编码成空格,想要传递&,被url处理成分隔符。所以都会做一下url转码的工作。

public class URLEncodeUtil {private final static String ENCODE = "UTF-8";/*** URL 解码*/public static String getURLDecoderString(String str) {String result = "";if (null == str) {return "";}try {result = java.net.URLDecoder.decode(str, ENCODE);} catch (UnsupportedEncodingException e) {e.printStackTrace();}return result;}/*** URL 转码*/public static String getURLEncoderString(String str) {String result = "";if (null == str) {return "";}try {result = java.net.URLEncoder.encode(str, ENCODE);} catch (UnsupportedEncodingException e) {e.printStackTrace();}return result;}
}

2.7全段页面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="/getQQCode">获取qq登录连接</a>
<div th:text="${url}"></div>
<a th:href="${url}">开始登录</a>
<br>
<a href="/wxLogin">跳到微信登录页</a>
</body>
</html>

2.8效果

授权后返回的信息

二、短信授权登录

短信登陆可以参考:微信开放平台官方文档

三、短信验证登录

我们使用阿里云短信服务来完成发送验证码

1.阿里云短息服务

进去阿里云,搜索短信服务,完成学习应该就了解的差不多了

1.添加签名和模板

  • 选择左侧的国内消
  • 签名管理中选择添加签名(签名就是发送短信时的程序名或公司名)需审核
  • 模板管理添加模板(也就是发送短信的内容)需审核

2.获取自己的阿里云私匙

  • 左侧点击概览
  • 选择AccessKey(获得私匙)

2.代码实现

可以参考OpenAPI Explorer

QQ第三方授权登录+阿里云短信服务相关推荐

  1. 如何使用阿里云短信服务实现登录页面,手机验证码登录?

    1:个人如何使用阿里云短信服务? 2022如何使用个人阿里云短信服务?_linxiMY的博客-CSDN博客添加完成之后,等待审核!一般2个小时就会出来审核结果了,这里我因为注册申请时填写规则有误,足足 ...

  2. 尚医通-阿里云短信服务(二十九)

    目录: (1)前台用户系统-手机登录-阿里云短信服务介绍 (2)手机登录-整合短信服务 (3)整合短信发送服务测试 (1)前台用户系统-手机登录-阿里云短信服务介绍 现在使用阿里云完成短信服务:注册登 ...

  3. 2022如何使用个人阿里云短信服务?

    点击登录阿里云短信服务控制台--->点击  添加签名  这里需要注意的时,因为现在阿里云管控的比较严格!!!要求申请之前必须有已经注册备案过的域名网站在使用!!!如果没有,就没必要往下面看了. ...

  4. 谷粒学院(十五)JWT | 阿里云短信服务 | 登录与注册前后端实现

    文章目录 一.使用JWT进行跨域身份验证 1.传统用户身份验证 2.解决方案 二.JWT令牌 1.访问令牌的类型 2.JWT的组成 3.JWT的原则 4.JWT的用法 三.整合JWT令牌 1.在com ...

  5. vue+springboot+阿里云短信服务(集成redis实现验证码登录业务)

    阿里云短信服务-介绍 阿里云短信服务(Short Message Service)是广大企业客户快速触达手机用户所优选使用的通信能力.调用API或用群发助手,即可发送验证码.通知类和营销类短信:国内验 ...

  6. 单点登录常见解决方式和阿里云短信服务

    1 单点登录(SSO) 三种常见方式: 1.1 第一种:session广播机制实现(已淘汰) 概念:就是session复制,一个模块登录后,该模块session存放用户登录信息,再把该session复 ...

  7. springboot+springsecurity+阿里云短信服务验证实现注册登录

    使用springboot+security+Aliyun短信服务实现注册登录 为了实现个人博客部分的登录注册,我采用了阿里云短信服务发送验证码,后端比对验证码的方式完成注册,现在功能还不完全,以后这个 ...

  8. 阿里云短信服务接口返回: 只能向已回复授权信息的手机号发送

    项目场景: 在进入阿里云短信服务时,调用 OpenAPI-发送短信接口 , 返回异常情况及其解决. 问题描述 在进入阿里云短信服务时, 调用测试签名和测试短信模板后, 返回只能向已回复授权信息的手机号 ...

  9. SpringBoot-短信验证码-快速入门Demo(含redis)(手把手教你开通阿里云短信服务到写出个最终代码来)

    B站小狂神-此博客的内容就是看了这个视频的总结(博主自己写的哦~并非转载) 视频链接-[狂神说]通俗易懂的阿里云短信业务实战教程(露脸) 您是否还在为别人的项目有短信功能自己的却没有? 您是否还在为自 ...

最新文章

  1. PHP面试中常见的字符串与文件操作题目
  2. 未来,谁来为AI开源买单?科技圈顶级码农是这样看的 | CCF C³-04@百度
  3. mysql x key 组合_技本功丨浅谈MySQL的七种锁
  4. 姿态估计之Yaw Pitch Roll
  5. 几家大的券商的PB系统以及算法交易概况大致是怎样的?
  6. Repository does not allow updating assets 解决方法
  7. ASIC和FPGA设计流程
  8. BES2300x笔记(4) -- TWS组对与蓝牙配对(Peer or Pair傻傻分不清)
  9. unity3d-unet小demo
  10. 腾讯多媒体实验室画质增强技术的前沿应用
  11. 读书笔记:《软件架构师应该知道的97件事》
  12. MIR7创建预制发票BAPI
  13. 后羿采集器怎么导出数据_免费爬虫工具:后羿采集器如何采集同花顺圈子评论数据...
  14. 【软件测试教程】手机号码归属地开发文档
  15. 【优化求解】基于加权黑猩猩算法WCHoA求解单目标问题matlab源码
  16. HTML+CSS的简单使用(代码)
  17. 开题报告:基于java电子商务购物商城网站系统 毕业设计论文开题报告模板
  18. office2019下载
  19. 实验室安全 考试 题库
  20. Hive Show命令

热门文章

  1. MathType中如何批量修改公式字体和大小
  2. 2023年黑马程序员Java学习路线图
  3. 黑马程序员前端-CSS练手之学成在线页面制作
  4. SHL、SHR指令的区别
  5. IIS误删了默认网站,恢复方法
  6. 爬虫获取网易云音乐单曲或歌单实现音乐闹钟
  7. 这个弹丸小国,靠移民收割不少国人
  8. 裂脑DNS(Split DNS)的那点旧事研究
  9. Wx腾讯 微信生成二维码--->微信扫描后注册并登录
  10. 【LeetCode 459 】重复的子字符串