qq 第三方登錄 前後端實現

 

 微信掃一掃關注個公衆號。謝謝各位

第一步:https://connect.qq.com/去此網站進行授權(需要用到域名,域名需要備案通過)

審覈通過後。拿到appid

第二步:前端定義個按鈕,爲按鈕綁定好事件(client_id==appid)

window.location.href ="https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=******&state=register&redirect_uri="+encodeURI("http://zhdydet.xyz:8085/api/qqLogin");//http://zhdydet.xyz:8085/api/qqLogin===>回調地址(qq第三方)

 

第三步:編寫後臺回調代碼

//具體此代碼要根據業務來。我這邊用的是shiro權限框架。回調後。默認進行shiro登錄授權,以及根據openid進行添加和修改用戶信息

 

@RequestMapping("/qqLogin")
public void  qqLoginAfter(HttpServletResponse response, HttpServletRequest request) {
    try{
        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 Exception("QQ,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=" + QQHttpClient.CALLBACK;

        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;
          User user =   userService.selectByOpenId(openid);
        JSONObject jsonObject = QQHttpClient.getUserInfo(url);
        String avatarImg = jsonObject.getString("figureurl_qq");
        String nickname = jsonObject.getString("nickname");
        String gender = jsonObject.getString("gender");
        User user1 = new User();
        Subject subject = SecurityUtils.getSubject();
          if(user == null){
              user1.setRealName(nickname);
              user1.setPicture(avatarImg);
              user1.setOpenID(openid);
              user1.setUserName(openid);
              String salt = getSalt();
              user1.setSalt(salt);
              String password = MD5Utils.MD5Encode(openid+"_"+salt+"_"+"123456","utf-8");
              user1.setPassword(password);
              user1.setRoleId(5);
              user1.setAddTime(new Date());
              this.userService.insertUser(user1);
              UsernamePasswordToken info = new UsernamePasswordToken(openid, "123456");
              subject.login(info);
             // response.sendRedirect("/api/index");
          }else{
              user1.setRealName(nickname);
              user1.setPicture(avatarImg);
              user1.setOpenID(openid);
              user1.setUserName(openid);
              user1.setId(user.getId());
              user1.setUpdateTime(new Date());
              this.userService.updateUser(user1);
              UsernamePasswordToken info = new UsernamePasswordToken(openid, "123456");
              subject.login(info);
          }
        redisTemplate.opsForValue().set("user:info"+":"+subject.getSession().getId(),user1,1L, TimeUnit.HOURS);

        response.sendRedirect("/api/index");
        response.setStatus(200);
    }catch (IOException e){

    }
}

 

 

QQHttpClient類

需要用到的maven依賴

<!--httpclient-->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version>
</dependency>

 

package com.bus.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 wwz
 * @date 2019-07-24
 * @descrption:
 */
public class QQHttpClient { //QQ互聯中提供的 appid 和 appkey
    public static final String APPID = "**********";

    public static final String APPKEY = "*********";
    public static final String CALLBACK = "http://zhdydet.xyz:8085/api/qqLogin";


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

感謝觀看,可以在微信搜索公衆號  威信交流,以後準備在 公衆號更新一些文章

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章