大连鹏鹏樱桃园 發表於 2020-1-10 11:33:00

Github 第三方授权登录教程

<h1>Github 第三方授权登录教程</h1>
<p>####大致流程图
<img src="http://o9beglkd1.bkt.clouddn.com/EC1E0F32-1617-4F20-B0DD-BF34092B2BD0.png"></p>
<p>####1.首先注册一个github帐号,Applications&gt;Developer applications&gt;Register a new application.
<img src="http://o9beglkd1.bkt.clouddn.com/47F731A9-CDCE-4F11-A0A8-63F32922CC2B.png">
<img src="http://o9beglkd1.bkt.clouddn.com/45462081-8750-492E-8B52-BE49EA3C548B.png">
####2.填入参数</p>
<ul>
<li>
<p><strong>Application name--应用名称,随意填</strong></p>
</li>
<li>
<p><strong>Homepage URL--如上图可以填本地地址进行测试,127.0.0.1:port/xx/xx</strong></p>
</li>
<li>
<p><strong>Application description--应用描述,随意填</strong></p>
</li>
<li>
<p><strong>Authorization callback URL--后端回调url,最重要的一环因为github那边回调会传你一个code参数,下面会提到.提交申请</strong></p>
</li>
<li>
<p><strong>注册之后会得到 github提供的client id和client secret有了这两个东东就可以换取更多的信息了,不要交给坏人0.0</strong></p>
</li>
</ul>
<p><img src="http://o9beglkd1.bkt.clouddn.com/87815A69-FF12-4141-B4C5-9DB6D3EA01F9.png"></p>
<p>####3.用户点击github登录本地应用引导用户跳转到第三方授权页 跳转地址为:
https://github.com/login/oauth/authorize?client_id=xxxxx&amp;state=xxx&amp;redirect_uri=xxxx;
(client_id 上面已经拿到了,state参数随便传多少,redirect_uri 就是你上面填的Authorization callback URL)
####4.授权成功后会回调我们平台,会重定向带参数访问我们上面的redirect_uri,后台接收code这个参数,我们带着这个code再次访问github 地址:
https://github.com/login/oauth/access_token?client_id=xxx&amp;client_secret=xxx&amp;code=xxx&amp;redirect_uri=http://127.0.0.1:8080/cqput-bbs/User/RegisteredByGithub.do
(这次会得到响应的access_token)
####5.成功获取access_token后就可以换取用户信息了地址:
https://api.github.com/user?access_token=xxx;
####(注意一下,这里会有个坑,4,5步骤都尽量用get请求去访问,第5步骤后端必须是模拟http get请求才能正确访问拿到返回值,post 请求 直接报404)</p>
<p>####6.得到github授权用户的个人信息,就可以插入到我们的数据库中去了,授权登录成功,跳转主页
<img src="http://o9beglkd1.bkt.clouddn.com/6837562C-0AB8-4FAE-99D5-0E7FA8B3B15E.png"></p>
<p>####代码:</p>
<pre><code class="language-java">/**
       * 授权github用户登录
       * @return
       */
        @RequestMapping(value="RegisteredByGithub")//callback url
        @ResponseBody
        public JSONObject RegisteredByGithub(String code){



                String me =CommonUtil.sendPost
                                ("https://github.com/login/oauth/access_token?client_id="+ParamUtil.client_id+"&amp;client_secret="+ParamUtil.client_secret+"&amp;code="+code+"&amp;redirect_uri=http://127.0.0.1:8080/cqput-bbs/User/RegisteredByGithub.do",null);

                String atoke = me.split("&amp;");

                String res = CommonUtil.sendGet("https://api.github.com/user?"+atoke+"");
                JSONObject user = (JSONObject) JSON.parse(res);

                return CommonUtil.constructResponse(1,"user_Person_Notice",user);
        }



/**
   * 向指定 URL 发送POST方法的请求
   *
   * @param url
   *            发送请求的 URL
   * @param param
   *            请求参数,请求参数应该是 name1=value1&amp;name2=value2 的形式。
   * @return 所代表远程资源的响应结果
   */
    public static String sendPost(String url, String param) {
      PrintWriter out = null;
      BufferedReader in = null;
      String result = "";
      try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                  "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            InputStream instream = conn.getInputStream();
            if(instream!=null){
                in = new BufferedReader( new InputStreamReader(instream));
                String line;
                while ((line = in.readLine()) != null) {
                  result += line;
                }
            }


      } catch (Exception e) {

            e.printStackTrace();

      }
      //使用finally块来关闭输出流、输入流
      finally{
            try{
                if(out!=null){
                  out.close();
                }
                if(in!=null){
                  in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
      }

      return result;
    }
    /**
   * 发起http请求获取返回结果
   * @param req_url 请求地址
   * @return
   */
    public static String sendGet(String req_url) {
      StringBuffer buffer = new StringBuffer();
      try {
            URL url = new URL(req_url);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();

            httpUrlConn.setDoOutput(false);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);

            httpUrlConn.setRequestMethod("GET");
            httpUrlConn.connect();

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            //res = new String(buffer.toString().getBytes("iso-8859-1"),"utf-8");
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();

      } catch (Exception e) {
            e.printStackTrace();
      }
      return buffer.toString();
    }
</code></pre><br><br>
来源:https://www.cnblogs.com/alannever/p/12175330.html
頁: [1]
查看完整版本: Github 第三方授权登录教程