zoukankan      html  css  js  c++  java
  • java实现QQ互联登录

    yml配置

    server:
      port: 80
     
    qq:
      oauth:
        http: //QQ互联中填写的网站地址

    导入pom依赖

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

    QQController

    package com.ck.blog.controller;
     
    import com.alibaba.fastjson.JSONObject;
    import com.ck.blog.exception.StateErrorException;
    import com.ck.blog.utils.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.HttpSession;
    import java.net.URLEncoder;
    import java.util.UUID;
     
    /**
     * @author ck
     * @create 2019-05-18 20:32
     */
    @Controller
    public class QQController {
     
     
        @Value("${qq.oauth.http}")
        private String http;
     
        /**
         * 发起请求
         * @param session
         * @return
         */
        @GetMapping("/qq/oauth")
        public String qq(HttpSession session){
            //QQ互联中的回调地址
            String backUrl = http + "/qq/callback";
     
            //用于第三方应用防止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=" + URLEncoder.encode(backUrl) +
                    "&state=" + uuid;
     
            return "redirect:" + url;
        }
     
        /**
         * QQ回调
         * @param request
         * @return
         */
        @GetMapping("/qq/callback")
        public String qqcallback(HttpServletRequest request) 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 + "/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);
     
            //也可以放到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:/home";
        }
     
    }

    QQHttpClient

    package com.ck.blog.utils;
     
    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;
     
    /**
     * @author ck
     * @create 2019-05-18 20:32
     * QQ工具类(主要用于解析QQ返回的信息)
     */
    public class QQHttpClient {
        //QQ互联中提供的 appid 和 appkey
        public static final String APPID = "xxxxxxxx";
     
        public static final String APPKEY = "xxxxxxxxxx";
     
     
        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;
        }
    }

    原文地址:https://blog.csdn.net/weixin_42140261/article/details/95456804
     
     
  • 相关阅读:
    SSH框架(一)Hibernate
    我要创业啦(基于MVC的在线教育系统)
    面向对象语言高并发技术数据库部分(一)----MyCat做MySQL负载均衡(享学课堂,咕泡学院听课笔记)
    数据库优化MySQL数据库性能优化(享学课堂听课笔记)
    系统集成项目管理工程师考试(经历)
    CSND使用(一直在学习)
    仓央嘉措不负如来不负卿
    Java与.net的选择和比较
    .Net编程之Web Service 和WCF的历史和特性
    .Net项目之分享自己的MVC+angularjs项目经历
  • 原文地址:https://www.cnblogs.com/niudaxianren/p/12692496.html
Copyright © 2011-2022 走看看