天天看点

qq 第三方登录 前后端实现

 微信扫一扫关注个公众号。谢谢各位

qq 第三方登录 前后端实现

第一步:https://connect.qq.com/去此网站进行授权(需要用到域名,域名需要备案通过)

qq 第三方登录 前后端实现

审核通过后。拿到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;
    }
}
           

感谢观看,可以在微信搜索公众号  威信交流,以后准备在 公众号更新一些文章