首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >网站实现QQ登录

网站实现QQ登录

作者头像
张苹果
发布于 2022-09-22 10:13:13
发布于 2022-09-22 10:13:13
7.7K0
举报
文章被收录于专栏:vaevae

一,申请QQ互联

  1. 申请地址:https://connect.qq.com/index.html

1,填写个人信息和网站信息后审核,确保审核通过后进行下一步。

2,注意网站信息要与备案时填写的一致,详细过程已省略(当我被拒了四五次后......终于审核通过了!!!)。

二,后端java代码

  1. 由于我是前后端分离,前端vue,部分可能代码不一致。
  2. 详细信息请访问原文地址或百度。

1,properties或yml配置

PlainBashC++C#CSSDiffHTML/XMLJavaJavascriptMarkdownPHPPythonRubySQL

#qq互联

qq.oauth.http=https://zhangweicheng.xyz

2,导入pom依赖

PlainBashC++C#CSSDiffHTML/XMLJavaJavascriptMarkdownPHPPythonRubySQL

<!--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>

3,创建QQController

PlainBashC++C#CSSDiffHTML/XMLJavaJavascriptMarkdownPHPPythonRubySQL

package com.example.myvue.controller;

import com.alibaba.fastjson.JSONObject;

import com.example.myvue.pojo.Users;

import com.example.myvue.service.UsersService;

import com.example.myvue.util.JavaWebToken;

import com.example.myvue.util.QQHttpClient;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.CrossOrigin;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import java.net.URLEncoder;

import java.util.HashMap;

import java.util.Map;

import java.util.UUID;

/**

* @author zwc

* @create 2022-2-17

*/

@Controller

@ResponseBody

@CrossOrigin

public class QQController {

//用户

@Autowired

UsersService usersService;

@Value("${qq.oauth.http}")

private String http;

/**

* 发起请求

* @param session

* @return

*/

@GetMapping("/qq/oauth")

public String qq(HttpSession session){

//QQ互联中的回调地址

// String backUrl = http + "https://zhangweicheng.xyz/api/qq/callback";

String backUrl = "https://zhangweicheng.xyz/api/qq/callback";

//用于第三方应用防止CSRF攻击

String uuid = UUID.randomUUID().toString().replaceAll("-","");

session.setAttribute("state",uuid);

//URLEncoder.encode(

//Step1:获取Authorization Code

String url = "https://graph.qq.com/oauth2.0/authorize?response_type=code"+

"&client_id=" + QQHttpClient.APPID +

"&redirect_uri=" + backUrl +

"&state=" + uuid;

return url;

}

/**

* QQ回调

* @param request

* @return

*/

@GetMapping("/qq/callback")

public void qqcallback(HttpServletRequest request, HttpServletResponse resp) throws Exception {

// HttpSession session = request.getSession();

String code = request.getParameter("code");

String state = request.getParameter("state");

String uuid = (String) session.getAttribute("state");

if(uuid != null){

if(!uuid.equals(state)){

// throw new StateErrorException("QQ,state错误");

}

}

//Step2:通过Authorization Code获取Access Token

String backUrl = http + "/api/qq/callback";

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=" + backUrl;

String access_token = QQHttpClient.getAccessToken(url);

//Step3: 获取回调后的 openid 值

url = "https://graph.qq.com/oauth2.0/me?access_token=" + access_token;

String openid = QQHttpClient.getOpenID(url);

//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);

//存入cookie中,也可以放到Redis和mysql中

//openid,用来唯一标识qq用户

//(String)jsonObject.get("nickname")); QQ名

//(String)jsonObject.get("figureurl_qq_2")); //大小为100*100像素的QQ头像URL

Cookie cookie1=new Cookie("qqName",(String)jsonObject.get("nickname"));

cookie1.setPath("/");

resp.addCookie(cookie1);

//由于是前后端分离,所以直接跳转首页地址

resp.sendRedirect("https://zhangweicheng.xyz/");

}

}

4,创建QQ工具类QQHttpClient

PlainBashC++C#CSSDiffHTML/XMLJavaJavascriptMarkdownPHPPythonRubySQL

package com.example.myvue.util;

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;

/**

* QQ工具类(主要用于解析QQ返回的信息)

*/

public class QQHttpClient {

//QQ互联中提供的 appid 和 appkey

public static final String APPID = "xxxxxx";

public static final String APPKEY = "xxxxxxxxx";

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);

}

public static String getAccessToken(String url) throws IOException {

CloseableHttpClient client = HttpClients.createDefault();

String token = null;

HttpGet httpGet = new HttpGet(url);

HttpResponse response = client.execute(httpGet);

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;

}

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;

}

}

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;

}

}

5,前端代码

PlainBashC++C#CSSDiffHTML/XMLJavaJavascriptMarkdownPHPPythonRubySQL

methods: {

//qq登录

qqBtn(){

this.$axios.get('/api/qq/oauth').then(res=>{

window.open(res.data,'_self')

}).catch(error=>{

console.error(error)

})

},

}

到此差不多结束了,明天又要上班咯;再顺便说一句:由于我的数据库用户表刚开始没有考虑到QQ登录的用户,所以赶紧连夜加班,修改了表结构,唉..麻烦死辽。。。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022/02/20 ,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • 一,申请QQ互联
    • 1,填写个人信息和网站信息后审核,确保审核通过后进行下一步。
    • 2,注意网站信息要与备案时填写的一致,详细过程已省略(当我被拒了四五次后......终于审核通过了!!!)。
  • 二,后端java代码
    • 1,properties或yml配置
    • 2,导入pom依赖
    • 3,创建QQController
    • 4,创建QQ工具类QQHttpClient
    • 5,前端代码
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档