java實現QQ登錄

2021-02-13 全棧開發者社區

點擊上方[全棧開發者社區]右上角[...][設為星標⭐]

準備工作

1.雲伺服器

2.備案的域名

3.本地調試需要修改hosts文件,將域名映射到127.0.0.1

一、申請QQ互聯,並成為開發者

QQ互聯:https://connect.qq.com/index.html

登錄後,點擊頭像,進入認證頁面,填寫信息,等待審核。

 審核通過後,點擊創建應用

審核通過後,就可以使用APP ID 和 APP Key

二、編寫java代碼

項目結構

yml配置

server:  port: 80 qq:  oauth:    http: //QQ互聯中填寫的網站地址

導入pom依賴

<dependency>    <groupId>org.apache.httpcomponents</groupId>    <artifactId>httpclient</artifactId>    <version>4.5.6</version></dependency><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; @Controllerpublic class QQController {      @Value("${qq.oauth.http}")    private String http;         @GetMapping("/qq/oauth")    public String qq(HttpSession session){                String backUrl = http + "/qq/callback";                 String uuid = UUID.randomUUID().toString().replaceAll("-","");        session.setAttribute("state",uuid);                 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;    }         @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錯誤");            }        }                  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);                 url = "https://graph.qq.com/oauth2.0/me?access_token=" + access_token;        String openid = QQHttpClient.getOpenID(url);                 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);                 session.setAttribute("openid",openid);          session.setAttribute("nickname",(String)jsonObject.get("nickname"));         session.setAttribute("figureurl_qq_2",(String)jsonObject.get("figureurl_qq_2"));          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; public class QQHttpClient {        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;    }}

IndexController 

package com.ck.blog.controller; import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping; import javax.servlet.http.HttpSession; @Controllerpublic class IndexController {     @GetMapping("/index")    public String index(){        return "index";    }     @GetMapping("/home")    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 "home";    }}

index.html


<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org"><head> <meta charset="UTF-8"> <title>登錄頁</title></head><body><a href="/qq/oauth">QQ授權登錄</a></body></html>

home.html

<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org"><head>    <meta charset="UTF-8">    <title>QQ授權成功</title></head><body><div>    openid:[[${openid}]]</div><div>    nickName:[[${nickname}]]</div><div>    <img th:src="${figureurl_qq_2}"></div></body></html>

效果圖

留言打卡第20天。

覺得本文對你有幫助?請分享給更多人

關注「全棧開發者社區」加星標,提升全棧技能

本公眾號會不定期給大家發福利,包括送書、學習資源等,敬請期待吧!

如果感覺推送內容不錯,不妨右下角點個在看轉發朋友圈或收藏,感謝支持。

好文章,我在看❤️

相關焦點

  • Java 實現 qq 登錄
    登錄後,點擊頭像,進入認證頁面,填寫信息,等待審核。二、編寫java代碼項目結構;import java.util.UUID; @Controllerpublic class QQController { @Value("${qq.oauth.http}") private String http; @GetMapping("/qq/oauth") public String qq(HttpSession session){
  • Java實現QQ登錄
    /index.html登錄後,點擊頭像,進入認證頁面,填寫信息,等待審核。二、編寫java代碼項目結構;import java.util.UUID; @Controllerpublic class QQController { @Value("${qq.oauth.http}") private String http; @GetMapping("/qq/oauth") public String qq(HttpSession session){
  • Java 實現第三方 QQ 帳號登錄
    -- 第三方QQ登錄 --><dependency>    <groupId>com.qq</groupId>    <artifactId>Sdk4J</artifactId>    <version>2</version></dependency>
  • 用Java實現了第三方qq帳號登錄...
    -- 第三方QQ登錄 --><dependency>    <groupId>com.qq</groupId>    <artifactId>Sdk4J</artifactId>    <version>2</version></dependency>
  • Java實現QQ登錄和微博登錄
    既然是對接第三方登錄,那就免不了如何將用戶信息保存。首先需要明確一點的是,用戶在第三方登錄成功之後,我們能拿到的僅僅是一個代表用戶唯一身份的ID(微博是真實uid,QQ是加密的openId)以及用來識別身份的accessToken,當然還有暱稱、頭像、性別等有限資料,對接第三方登錄的關鍵就是如何確定用戶是合法登錄,如果確定這次登錄的和上次登錄的是同一個人並且不是假冒的。
  • 基於Java實現QQ登錄和微博登錄
    今天跟大家分享基於Java實現QQ登錄和微博登錄的知識。
  • SpringBoot實現QQ郵箱註冊和登錄
    >1、登錄註冊思路這是一個使用spring boot做的一個qq郵箱註冊和登錄的項目。1.1、思路註冊:通過輸入的郵箱發送驗證碼,檢驗前端傳來的驗證碼是否和後臺生成的一致,若一致,將數據寫入資料庫,完成註冊;登錄:通過輸入的郵箱查詢密碼,然後比較密碼是否一致,一致就是登錄成功。1.2、整個項目結構圖
  • Spring-Security-入門(六):QQ登錄實現
    2、了解QQ登錄時的 網站應用接入流程。3、登錄 -> QQ登錄 -> 個人中心,將會看到個人信息。;import java.util.regex.Matcher;import java.util.regex.Pattern;public class QQAuthenticationFilter extends AbstractAuthenticationProcessingFilter {    private final static String
  • SpringBoot 實現 QQ 郵箱註冊和登錄
    這是一個使用spring boot做的一個qq郵箱註冊和登錄的項目。沒寫前端頁面,使用postman測試。有截圖詳細。1.1、思路註冊:通過輸入的郵箱發送驗證碼,檢驗前端傳來的驗證碼是否和後臺生成的一致,若一致,將數據寫入資料庫,完成註冊;登錄:通過輸入的郵箱查詢密碼,然後比較密碼是否一致,一致就是登錄成功。1.2、整個項目結構圖
  • SpringBoot實現QQ郵箱註冊和登錄詳解
    _425242881、登錄註冊思路這是一個使用spring boot做的一個qq郵箱註冊和登錄的項目。1.1、思路註冊:通過輸入的郵箱發送驗證碼,檢驗前端傳來的驗證碼是否和後臺生成的一致,若一致,將數據寫入資料庫,完成註冊;登錄:通過輸入的郵箱查詢密碼,然後比較密碼是否一致,一致就是登錄成功。1.2、整個項目結構圖2、準備2.1、開啟郵箱POP3/SMTP服務登錄qq郵箱後,點擊左上方的設置,選擇帳戶,如下圖。
  • Java實戰:50行代碼實現QQ登錄和微博登錄
    另外一個問題就是如何和現有用戶系統打通,有的網站在用戶已經登錄成功之後還要用戶輸入手機號和驗證碼,或者要用戶重新註冊帳號和密碼來綁定第三方帳戶,感覺這種實現用戶體驗非常差,碰到這種網站我一般都是直接關掉,都已經登錄了還讓用戶註冊,什麼鬼!
  • CAS Server集成QQ登錄、新浪微博登錄源碼及配置文件
    CAS Server(cas-server3.5.2)實現qq第三方登錄,並分享一下實現代碼和具體配置文件內容,雖然包含新浪微博登錄但是未經測試,有什麼疑問可留言。cas-server集成QQ第三方登錄1、打開cas-server工程中cas-server-support-oauth子項目,創建QQApi20.java類文件名稱並繼承DefaultApi20.java類,具體代碼如下:package org.jasig.cas.support.oauth.qq;import org.jasig.cas.support.oauth.OAuthConstants
  • SpringBoot項目 qq郵箱驗證碼註冊和登錄
    1、登錄註冊思路這是一個使用spring boot做的一個qq郵箱註冊和登錄的項目。
  • JAVA實現qq郵箱發送(Java Mail)
    > http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd "> <bean id="javaMailSender
  • Java--app微信第三方登錄
    Java--app微信第三方登錄此篇文章是POI導出Word文件的案例,親測後分享。參考網站:https://blog.csdn.net/zhibo112/article/details/50656443微信登錄流程 1.流程圖
  • PHP實現QQ登錄的原理和實現過程
    (商務合作聯繫QQ號:2230304070)http://www.jb51.net/article/134362.htm第三方登錄,就是使用大家比較熟悉的比如QQ、微信、微博等第三方軟體登錄自己的網站,這可以免去註冊帳號、快速留住用戶的目的,免去了相對複雜的註冊流程
  • 黑客QQ教程,第三方帳號登錄!
    QQ互聯註冊一個帳號網站地址:https://connect.qq.com/,添加一個應用,具體怎麼申請以及需要填寫的信息,騰訊官網有詳細文檔。註冊並完成相應信息填寫後,可以在應用管理中查到應用的APP ID和APP Key。
  • Spring Boot qq郵箱驗證碼註冊和登錄驗證
    1、登錄註冊思路 這是一個使用spring boot做的一個qq郵箱註冊和登錄的項目。沒寫前端頁面,使用postman測試。有截圖詳細。1.1、思路註冊:通過輸入的郵箱發送驗證碼,檢驗前端傳來的驗證碼是否和後臺生成的一致,若一致,將數據寫入資料庫,完成註冊;登錄:通過輸入的郵箱查詢密碼,然後比較密碼是否一致,一致就是登錄成功。
  • 單點登錄原理和java實現簡單的單點登錄
    本文從業務的角度分析了單點登錄的需求和應用領域;從技術本身的角度分析了單點登錄技術的內部機制和實現手段,並且給出Web-SSO和桌面SSO的實現、原始碼和詳細講解;還從安全和性能的角度對現有的實現技術進行進一步分析,指出相應的風險和需要改進的方面。
  • java web使用Cookie實現3天免登錄功能
    引言:在這樣的一個業務場景下,進入到網站登錄帳號要求記住帳號和密碼,用戶退出之後,瀏覽器能夠記住用戶的帳號和密碼,下次登錄網站不需要輸入帳號和密碼就能夠登錄帳號