实现GitHub第三方登陆详细过程 - Go语言中文社区

实现GitHub第三方登陆详细过程


  • 第一步:登陆GitHub官网注册账号登陆后:
    在这里插入图片描述
  • 第二步:创建一个应用并填写信息
    在这里插入图片描述在这里插入图片描述在这里插入图片描述
    在这里插入图片描述
  • 第四步:在前台准备一个按钮用于GitHub账号登陆:
<a href="https://github.com/login/oauth/authorize?client_id=对应自己申请的client id
&state=STATE&redirect_uri=http://localhost/callback;">github登录</a>

注意:redirect_uri是回调地址,必须和在注册应用时候填写的回调地址一致。

  • 第五步:准备java代码,这步中的部分方法和常量依赖于后面的:【常量类】、【自定义工具类】
package cn.itsource.crm.web.controller;

import cn.itsource.crm.domain.Github;
import cn.itsource.crm.service.IGithubService;
import cn.itsource.util.GitHubConstant;
import cn.itsource.util.HttpClientUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Created with IDEA
 * @author: Super Zheng
 * @Description: 第三方登陆GitHub
 * @Date:2018/12/26
 * @Time:18:59
 */
@Controller
public class GithubLoginController {

    @Autowired
    private IGithubService githubService;
	//回调地址
    @RequestMapping("/callback")
    public String callback(String code, String state, Model model, HttpServletRequest req) throws Exception{

        if(!StringUtils.isEmpty(code)&&!StringUtils.isEmpty(state)){
            //拿到我们的code,去请求token
            //发送一个请求到
            String token_url = GitHubConstant.TOKEN_URL.replace("CODE", code);
	 	    //得到的responseStr是一个字符串需要将它解析放到map中
            String responseStr = HttpClientUtils.doGet(token_url);
            // 调用方法从map中获得返回的--》 令牌
            String token = HttpClientUtils.getMap(responseStr).get("access_token");

            //根据token发送请求获取登录人的信息  ,通过令牌去获得用户信息
            String userinfo_url = GitHubConstant.USER_INFO_URL.replace("TOKEN", token);
            responseStr = HttpClientUtils.doGet(userinfo_url);//json

            Map<String, String> responseMap = HttpClientUtils.getMapByJson(responseStr);
            // 成功则登陆
            return "/main";
        }
        // 否则返回到登陆页面
        return "/login/login";
    }
}

  • 代码中的常量字段:
package cn.itsource.util;

/**
 * @Created with IDEA
 * @author: Super Zheng
 * @Description: java类作用描述
 * @Date:2018/12/26
 * @Time:12:20
 */
public class GitHubConstant {
    // 这里填写在GitHub上注册应用时候获得 CLIENT ID
    public static final String  CLIENT_ID="a7dc7e3d";
	//这里填写在GitHub上注册应用时候获得 CLIENT_SECRET
    public static final String CLIENT_SECRET="1faa46333a4d1c904";
    // 回调路径
    public static final String CALLBACK = "http://localhost/callback";

    //获取code的url
    public static final String CODE_URL = "https://github.com/login/oauth/authorize?client_id="+CLIENT_ID+"&state=STATE&redirect_uri="+CALLBACK+"";
    //获取token的url
    public static final String TOKEN_URL = "https://github.com/login/oauth/access_token?client_id="+CLIENT_ID+"&client_secret="+CLIENT_SECRET+"&code=CODE&redirect_uri="+CALLBACK+"";
    //获取用户信息的url
    public static final String USER_INFO_URL = "https://api.github.com/user?access_token=TOKEN";

}

  • 第三方登陆工具类中用到的依赖包:
<dependencies>
        <!--java代码发送请求依赖包-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>
        <!--将json转换成map-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
  </dependencies>
  • 第三方登陆工具类:
package cn.itsource.util;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.util.HashMap;
import java.util.Map;

/**
 * @Created with IDEA
 * @author: Super Zheng
 * @Description: java类作用描述
 * @Date:2018/12/26
 * @Time:12:58
 */
public class HttpClientUtils {

    /**
     * 发送get请求,利用java代码发送请求
     * @param url
     * @return
     * @throws Exception
     */
    public static String doGet(String url) throws Exception{

        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(url);
        // 发送了一个http请求
        CloseableHttpResponse response = httpclient.execute(httpGet);
        // 如果响应200成功,解析响应结果
        if(response.getStatusLine().getStatusCode()==200){
            // 获取响应的内容
            HttpEntity responseEntity = response.getEntity();

            return EntityUtils.toString(responseEntity);
        }
        return null;
    }

    /**
     * 将字符串转换成map
     * @param responseEntity
     * @return
     */
    public static Map<String,String> getMap(String responseEntity) {

        Map<String, String> map = new HashMap<>();
        // 以&来解析字符串
        String[] result = responseEntity.split("\&");

        for (String str : result) {
            // 以=来解析字符串
            String[] split = str.split("=");
            // 将字符串存入map中
            if (split.length == 1) {
                map.put(split[0], null);
            } else {
                map.put(split[0], split[1]);
            }

        }
        return map;
    }

    /**
     * 通过json获得map
     * @param responseEntity
     * @return
     */
    public static Map<String,String> getMapByJson(String responseEntity) {
        Map<String, String> map = new HashMap<>();
        // 阿里巴巴fastjson  将json转换成map
        JSONObject jsonObject = JSONObject.parseObject(responseEntity);
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            String key = entry.getKey();
            // 将obj转换成string
            String value = String.valueOf(entry.getValue()) ;
            map.put(key, value);
        }
        return map;
    }
}

  • 第六步:测试
    -在这里插入图片描述
    在这里插入图片描述
  • 总结:整体原理分析:
    在这里插入图片描述
版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/suprezheng/article/details/85298011
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-06-27 23:35:55
  • 阅读 ( 1263 )
  • 分类:Go开源项目

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢