zoukankan      html  css  js  c++  java
  • QQ第三方登录

    应用场景#

    web应用通过QQ登录授权实现第三方登录

    操作步骤#

    1. 首先要有一个自己可以访问的网址.(www.xxx.com).
    2. 然后在QQ互联平台验证域名信息,设置回调地址.如:http://graph.qq.com/demo/index.jsp
    3. 获取AppId,AppKey进行开发

    具体实现方式#

    登录按钮##

    将请求的路径写入a标签中

    <a href="https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=*****&redirect_uri=*****&state=*****&scope=get_user_info,getinfo">
    

    打*号指的是都要自己填写

    • client_id是AppId
    • redirect_uri是回调的方法
    • state是用于校验的参数,是由自己制定的密钥,在回调的方法里会一同返回.

    回调方法##

    StringBuffer callBackUrl = request.getRequestURL();
    String code = request.getParameter("code");//得到回调请求所带的参数
    String dialog_url="https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id="+qq_app_id+"&redirect_uri="+callBackUrl+"&state=1&client_secret="+qq_app_key+"&code="+code;//使用code发起新的请求
    String apiResult = getApiResult(dialog_url);
    //如果成功返回,即可在返回包中获取到Access Token
    //如:apiResult = "access_token=FE04************************CCE2&expires_in=7776000&refresh_token=88E4************************BE14"
    String access_token = apiResult.substring(apiResult.indexOf("=")+1, apiResult.indexOf("&"));//字符串分割得到access_token 
    String refresh_token = apiResult.substring(apiResult.lastIndexOf("=")+1);//字符串分割得到refresh_token 
    
    • 已经获取了access_token,就可以以此获取openId,每个qq用户的openId都是唯一的.
    String dialog_url2 = "https://graph.qq.com/oauth2.0/me?access_token="+access_token;
    String apiResult = getApiResult(dialog_url2);//返回值如下:allback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} );
    String jsonStr = apiResult.substring(apiResult.indexOf("(")+1, apiResult.indexOf(")"));//截取字符串
    JSONObject jo = JSONObject.fromObject(jsonStr);//用net.sf.json.JSONObject对该字符串进行解析
    String openId = jo.getString("openid");//获取其中的openId
    
    • 最后,用openId获取用户的信息吧
    String dialog_url3 = "https://graph.qq.com/user/get_user_info?access_token="+access_token+"&oauth_consumer_key="+qq_app_id+"&openid="+openId;
    String apiResult = getApiResult(dialog_url3);
    //返回的参数
    //以json形式返回{"ret":0,"msg":"","nickname":"YOUR_NICK_NAME",...},通过解析就可得到想要的参数
    
    • 这是我抽象出来的getApiResult方法
    public String getApiResult(String url) throws IOException{
    	URL apiUrl = new URL(url);
    	URLConnection conn= apiUrl.openConnection();
    	InputStream in = conn.getInputStream();
    	String result = IOUtils.toString(in);
    	return result;
    }
    
  • 相关阅读:
    SpringCloud整合过程中jar依赖踩坑经验
    spring-boot-starter-parent的主要作用
    配置Setting.xml文件提高maven更新下载jar包速度
    剑指Offer-编程详解-二维数组中的查找
    Git 拉取Gitee仓库报错:“fatal: unable to access ''": Failed to connect to 127.0.0.1 port 1080: Connection refused”
    SpringBoot整合mybatis——配置mybatis驼峰命名规则自动转换
    SpringBoot 整合 Mybatis + Mysql——XML配置方式
    ES+open-falcon之nginx状态码监控报警自动化
    zabbix告警邮件美化
    基于Jenkins+Gitlab的自动化部署实战
  • 原文地址:https://www.cnblogs.com/itsrobin/p/5042162.html
Copyright © 2011-2022 走看看