Github 第三方授权登录教程

Github 第三方授权登录教程

####大致流程图 cmd-markdown-logo

####1.首先注册一个github帐号,Applications>Developer applications>Register a new application. cmd-markdown-logo cmd-markdown-logo ####2.填入参数

  • Application name--应用名称,随意填

  • Homepage URL--如上图可以填本地地址进行测试,127.0.0.1:port/xx/xx

  • Application description--应用描述,随意填

  • Authorization callback URL--后端回调url,最重要的一环因为github那边回调会传你一个code参数,下面会提到.提交申请

  • 注册之后会得到 github提供的client id和client secret有了这两个东东就可以换取更多的信息了,不要交给坏人0.0

cmd-markdown-logo

####3.用户点击github登录本地应用引导用户跳转到第三方授权页 跳转地址为: https://github.com/login/oauth/authorize?client_id=xxxxx&state=xxx&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&client_secret=xxx&code=xxx&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)

####6.得到github授权用户的个人信息,就可以插入到我们的数据库中去了,授权登录成功,跳转主页 cmd-markdown-logo

####代码:

/**
	 * 授权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+"&client_secret="+ParamUtil.client_secret+"&code="+code+"&redirect_uri=http://127.0.0.1:8080/cqput-bbs/User/RegisteredByGithub.do",null);

		String atoke = me.split("&")[0];

		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&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();
    }

猜你喜欢

转载自www.cnblogs.com/alannever/p/12175330.html