第三方登录(QQ版)
1:申请平台注册
接入QQ登录前,网站需首先进行申请,获得对应的appid与appkey,以保证后续流程中可正确对网站与用户进行验证与授权。
申请appid和appkey的用途
*appid*:应用的唯一标识。在OAuth2.0认证过程中,appid的值即为oauth_consumer_key的值。
appkey:appid对应的密钥,访问用户资源时用来验证应用的合法性。在OAuth2.0认证过程中,appkey的值即为oauth_consumer_secret的值。
QQ开放平台地址:腾讯开放平台beta|开放成就梦想
新用户进入到这个网址,首先点击应用开放平台
,进入到里面,进行登录,点击个人,并且按照要求补全个人信息
填写真实个人资料,不要瞎胡写,提交注册后,大概1-2天就会过审。还是在:腾讯开放平台beta|开放成就梦想 点击
点击qq开放平台,进去点击应用管理,审核通过。
2.应用申请
应用申请需要域名,完整的后端代码和前端的代码,前端代码里要有QQ登录的图标,并且后端代码有能访问的回调地址。如下图:
这里提供了完整的代码,导入完整的代码,导进去之后,只需要修改你的回调域,APPid,APPkey,剩下的不需要动。
解决Maven 第三方qq登录配置 爆红问题,将Sdk4J.jar放到D盘根目录下,并进入命令窗口
输入maven指令,将本地的jar包导入我们的maven库,如果提示mvn不是内部或者外部命令,是因为系统没有配置maven环境,这个阶段都会安装过maven了。
mvn install:install-file -Dfile="Sdk4J.jar" -DgroupId=com.xinzhi -DartifactId=sdk4j -Dversion=1.0.0 -Dpackaging=jar
将项目打包部署到服务器上,启动项目
部署完之后在返回到qq开放平台,创建应用
点击创建网站应用,注意进去之后一定要用你的域名创建,提供方,网站地址就是你的域名,(提供方,备案号就是咱们腾讯云上你域名那块就能显示出来)
创建完之后,大概七个工作日之内就会给你审核成功,过审之后就是这样子的
注意! 过审之后你的Appid Appkey会显示出来
注意!!代码中你的Appid,APPkey,回调域一定要改成你自己的!这块一定要注意!
重新打包项目部署到服务器上,并且启动,访问网站地址,点击qq图标就可以实现快速登录了
3.第三方登录
1.概念
所谓的第三方登录就是基于用户在第三方平台已有的账号和密码来快速实现对乙方应用的登录或注册的功能,
而这里的第三方登录是指拥有大量用户的平台,比如qq,微博,微信,等等一系列平台,
第三方登录的作用是用户在其他平台上频繁使用的账号来快速登录乙方应用,可以不注册也能快速登录。
2.为什么使用第三方登录
1.服务方希望用户注册, 而用户懒得填注册时的各种信息(主要是为了保证用户的唯一性,各种用户名已占用,密码格式限制).
2.而像微信, QQ, 微博等几乎每个人都会安装的应用中用户肯定会在其中某一个应用中已经注册过,证明该用户在已经注册的应用中的唯一性.
3.第三方登录的实质就是在授权时获得第三方应用提供的代表了用户在第三方应用中的唯一性的openid.并将openid储存在第三方服务控制的本地储存
3.好处
1.对于用户本身来说:大大节省了登录乙方应用的时间,不用注册,直接拿第三方平台的账号密码在不同的应用里快速登录,实现一个账号行走天下,同时也降低了用户注册登录的成本
2.对于第三方平台来说;大大增加了用户量,提升了曝光率
3.对于乙方应用来说:因为降低了用户的注册或登录成本,从而减少由于本地注册的繁琐性而带来的隐形用户流失,最终提高注册转化率。
4.通过授权,可以获得该用户在第三方平台上的好友或粉丝等社交信息,从而后续可以针对用户的社交关系网进行有目的性的营销宣传,为产品的市场推广提供另一种渠道。
4.缺点
一旦自己的第三方账户出现问题,比如被第三方平台封号,或者账号被盗,则会发生相应的应用内数据丢失或者数据泄露。这个时候即使注册一个新账户,之前在应用内所有的记录也是无法恢复的。
5.第三方登录实现流程
1:接入申请,获取Appid和Appkey;
2:放置QQ登录按钮
3:通过用户登录验证和授权,获取Access Token
4:通过Access Token获取用户的OpenID
5:调用OpenAPl,来请求访问或修改用户授权的资源
6.代码
第一步:导入Pom依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.11</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.xinzhi</groupId>
<artifactId>qdemo0516</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>qdemo0516</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!--httpclient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<!--阿里 JSON-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<!-- 第三方QQ登录 -->
<dependency>
<groupId>com.xinzhi</groupId>
<artifactId>sdk4j</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
<!-- mvn install:install-file -Dfile=Sdk4J.jar -DgroupId=groupId(分组) -DartifactId=artifactId(jar名称) -Dversion=version(版本号) -Dpackaging=jar-->
<!-- mvn install:install-file -Dfile="Sdk4J.jar" -DgroupId=com.xinzhi -DartifactId=sdk4j -Dversion=1.0.0 -Dpackaging=jar-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.创建Custom包,类名QQHttpClient
package com.xinzhi.custom;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class QQHttpClient {
//QQ互联中提供的 appid 和 appkey
public static final String APPID = "102049113";
public static final String APPKEY = "iKsCIAnERQBhy1qP";
//将JSONP返回的结果转化为Java对象
private static JSONObject parseJSONP(String jsonp){
int startIndex = jsonp.indexOf("(");
int endIndex = jsonp.lastIndexOf(")");
String json = jsonp.substring(startIndex + 1,endIndex);
return JSONObject.parseObject(json);
}
//qq返回信息:access_token=FE04************************CCE2&expires_in=7776000&refresh_token=88E4************************BE14
public static String getAccessToken(String url) throws IOException {
CloseableHttpClient client = HttpClients.createDefault();
String token = null;
HttpGet httpGet = new HttpGet(url);
// 调用HttpResponse的请求方法获取服务器的响应头
HttpResponse response = client.execute(httpGet);
// 调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容
HttpEntity entity = response.getEntity();
if(entity != null){
String result = EntityUtils.toString(entity,"UTF-8");
if(result.indexOf("access_token") >= 0){
String[] array = result.split("&");
for (String str : array){
if(str.indexOf("access_token") >= 0){
token = str.substring(str.indexOf("=") + 1);
break;
}
}
}
}
httpGet.releaseConnection();
return token;
}
//qq返回信息:callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} ); 需要用到上面自己定义的解析方法parseJSONP
public static String getOpenID(String url) throws IOException {
JSONObject jsonObject = null;
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
if(entity != null){
String result = EntityUtils.toString(entity,"UTF-8");
jsonObject = parseJSONP(result);
}
httpGet.releaseConnection();
if(jsonObject != null){
return jsonObject.getString("openid");
}else {
return null;
}
}
//qq返回信息:{ "ret":0, "msg":"", "nickname":"YOUR_NICK_NAME", ... },为JSON格式,直接使用JSONObject对象解析
public static JSONObject getUserInfo(String url) throws IOException {
JSONObject jsonObject = null;
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
if(entity != null){
String result = EntityUtils.toString(entity,"UTF-8");
jsonObject = JSONObject.parseObject(result);
}
httpGet.releaseConnection();
return jsonObject;
}
}
类名 QqLoginAppLication(启动类)
package com.xinzhi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class QqloginApplication {
public static void main(String[] args) {
SpringApplication.run(QqloginApplication.class, args);
}
}
创建Controller包,类名QQController
package com.xinzhi.controller;
import com.alibaba.fastjson.JSONObject;
import com.xinzhi.custom.QQHttpClient;
import com.xinzhi.custom.QQHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;
//QQ登录
@Controller
public class QQController {
@Value("${qq.oauth.http}")
private String http;
/**
* 发起请求
*
* @param session
* @return
*/
@GetMapping("/login/qq")
public String qq(HttpSession session) throws UnsupportedEncodingException {
//QQ互联中的回调地址
String backUrl = http + "/index";
//用于第三方应用防止CSRF攻击
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
session.setAttribute("state", uuid);
//Step1:获取Authorization Code
String url = "https://graph.qq.com/oauth2.0/authorize?response_type=code" +
"&client_id=" + QQHttpClient.APPID +
"&redirect_uri=" + http +
// URLEncoder.encode(backUrl, "UTF-8")+
"&state=" + uuid;
System.out.println(url);
return "redirect:" + url;
}
/**
* QQ回调
*
* @param request /qq/callback
* @return
*/
@GetMapping("/oauth/login/qq")
public String qqcallback(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
//qq返回的信息
String code = request.getParameter("code");
String state = request.getParameter("state");
System.out.println(code + "--" + state);
//Step2:通过Authorization Code获取Access Token
String url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code" +
"&client_id=" + QQHttpClient.APPID +
"&client_secret=" + QQHttpClient.APPKEY +
"&code=" + code +
"&redirect_uri=" + http;
String access_token = QQHttpClient.getAccessToken(url);
System.out.println("access_token:" + access_token);
//Step3: 获取回调后的 openid 值
url = "https://graph.qq.com/oauth2.0/me?access_token=" + access_token;
String openid = QQHttpClient.getOpenID(url);
System.out.println("openid:" + openid);
//Step4:获取QQ用户信息
url = "https://graph.qq.com/user/get_user_info?access_token=" + access_token +
"&oauth_consumer_key=" + QQHttpClient.APPID +
"&openid=" + openid;
//返回用户的信息
JSONObject jsonObject = QQHttpClient.getUserInfo(url);
//也可以放到Redis和mysql中,只取出了部分数据,根据自己需要取
session.setAttribute("openid", openid); //openid,用来唯一标识qq用户
session.setAttribute("nickname", (String) jsonObject.get("nickname")); //QQ名
session.setAttribute("figureurl_qq_2", (String) jsonObject.get("figureurl_qq_2")); //大小为100*100像素的QQ头像URL
return "redirect:/success";
}
}
类名 QQLoginController
package com.xinzhi.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpSession;
@Controller
public class QQLoginController {
@GetMapping({"/index", "/"})
public String index(){
return "index";
}
@GetMapping("/success")
public String home(HttpSession session, Model model){
String openid = (String) session.getAttribute("openid");
String nickname = (String) session.getAttribute("nickname");
String figureurl_qq_2 = (String) session.getAttribute("figureurl_qq_2");
model.addAttribute("openid",openid);
model.addAttribute("nickname",nickname);
model.addAttribute("figureurl_qq_2",figureurl_qq_2);
return "success";
}
}
resources下创建templates
index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta charset="utf-8">
<script src="js/jquery-2.1.4.min.js"></script>
<title>登录界面</title>
</head>
<body>
<center>
<h1 style="color:red">登录</h1>
<table border="0">
<tr>
<td>账号:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="text" name="password">
</td>
</tr>
</table>
<br>
<input type="submit" value="登录" style="color:#BC8F8F">
<input type="submit" value="注册" style="color:#BC8F8F"> <br>
第三方登录<br>------------------------------<br>
<a href="/login/qq">
<img id="qq" src="image/qq.jpg" width="30px" height="40px" style="cursor:pointer;"/>
</a>
<img id="weibo" src="image/weibo.jpg" width="35px" height="45px" style="cursor:pointer;"/>
<img id="weixin" src="image/weixin.jpg" width="40px" height="50px" style="cursor:pointer;"/>
<br><hr>
</center>
</body>
</html>
success.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta charset="utf-8">
<script src="js/jquery-2.1.4.min.js"></script>
<title>登录成功</title>
</head>
<body>
<center>
<h1>登录成功!欢迎您:</h1>
<div>
头像:<img th:src="${figureurl_qq_2}">
</div>
<span th:text="${openid}"></span>
昵称:<span th:text="${nickname}"></span>
</center>
</body>
<script type="text/javascript">
</script>
</html>
application.properties
server.port=80
qq.oauth.http=http://www.duola.fit/oauth/login/qq
qq.oauth.http=http://域名