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();
    }
  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
THINKPHP最全第三方登录(包括腾讯QQ、微信、新浪微博、Github、淘宝网、百度、搜狐微博、人人、360、网易等等) 使用方式: 1、使用命名空间 use Org\ThinkSDK\ThinkOauth; 2、设置三方登录的类别并赋予一个变量 $type = ThinkOauth::getInstance('qq'); 3、设置配置文件 'THINK_SDK_(TYPE)' => array( 'APP_KEY' => '', //应用注册成功后分配的 APP ID 'APP_SECRET' => '', //应用注册成功后分配的KEY 'CALLBACK' => '', //注册应用填写的callback ), 上文中的(TYPE)为设置的类别,其值目前有以下几个: //腾讯QQ登录配置 THINK_SDK_QQ // 用户基本信息API接口 user/get_user_info //腾讯微博配置 THINK_SDK_TENCENT // 用户基本信息API接口 user/info //新浪微博配 THINK_SDK_SINA // 用户基本信息API接口 users/show。附加参数:'uid='.$obj->openid() //网易微博配置 THINK_SDK_T163 // 用户基本信息API接口 users/show //人人网配置 THINK_SDK_RENREN // 用户基本信息API接口 users.getInfo //360配置 THINK_SDK_X360 // 用户基本信息API接口 user/me //豆瓣配置 THINK_SDK_DOUBAN // 用户基本信息API接口 user/~me //Github配置 THINK_SDK_GITHUB // 用户基本信息API接口 user //Google配置 THINK_SDK_GOOGLE // 用户基本信息API接口 userinfo //MSN配置 THINK_SDK_MSN // 用户基本信息API接口 msn。附加参数:token //点点配置 THINK_SDK_DIANDIAN // 用户基本信息API接口 user/info //淘宝网配置 THINK_SDK_TAOBAO // 用户基本信息API接口 taobao.user.buyer.get。附加参数:'fields=user_id,nick,sex,buyer_credit,avatar,has_shop,vip_info' //百度配置 THINK_SDK_BAIDU // 用户基本信息API接口 passport/users/getLoggedInUser // 注意,百度的头像位置是http://tb.himg.baidu.com/sys/portrait/item/{$data['portrait']} //开心网配置 THINK_SDK_KAIXIN // 用户基本信息API接口 users/me //搜狐微博配置 THINK_SDK_SOHU // 用户基本信息API接口 i/prv/1/user/get-basic-info 4、实例化一个登录页面 redirect($type->getRequestCodeURL()); 这里的$type是第二部获取的结果 5、回调页面 $code = $this->get('code'); $type = 'QQ'; $sns = ThinkOauth::getInstance($type); //腾讯微博需传递的额外参数 $extend = null; if($type == 'tencent'){ $extend = array('openid' => $this->_get('openid'), 'openkey' => $this->_get('openkey')); } //请妥善保管这里获取到的Tok

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值