oauth接入github登录记录

个人博客文章链接:http://www.huqj.top/article?id=143

博客网站评论需要接入第三方登录,这里记录下接入github登录和开发的全过程。

最终效果为如果不登录则无法评论,点击第三方登录(之后尝试接入其它平台)跳转到第三方授权,然后回到评论页面可以发表评论。

登录前:

image.png

登陆后:

image.png

其中头像和昵称都是从github获取的。

 

第一步:在github中申请创建oauth引用,就在github.com上就可以,不需要去额外的开放平台,如下图

image.png  image.png

image.png

这里我已经创建过了,所以有一个

image.png

如上图,主要是设置应用图标(给登录者看的),应用名称和回调地址等,其中回调地址最为重要,它是授权成功后github回调的url(会带上获取的code),一般需要自己来进行处理,具体后面再说。

 

第二步:编写回调处理方法

整个授权流程是这样的:(详见官方文档:https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps  )

  1. 开发者注册oauth app之后会得到client id和client secret

  2. 当需要引导用户登录的时候,跳转到 https://github.com/login/oauth/authorize (get请求并携带参数,如需要权限、回调地址、client id等)

  3. 当用户鉴权授权成功之后,会生成一个code,加在回调地址后面,也就是调用前面填写的回调地址

  4. 我们的应用拿到code之后,加上client id、client secret等参数可以获得access token,这个就像是一把钥匙,有了它我们就可以获取用户在github上的信息了。

理解了上面的流程,我们在回调处理中应该做的事情就比较明确了:

  1. 通过code获取access token

  2. 通过access token获取用户信息,并且如果是初次登录最好将信息保存在数据库中避免之后重复获取。(注意这会带来信息时效性问题,最好定期更新

  3. 为了让用户登录在一定时间内保存,我们需要给客户端加上一个cookie标识登录状态,之后通过这个cookie判断是否已经登录。

  4. 返回到原本想要访问的页面(这里就是评论页面),这是会携带cookie,通过cookie就可以判断已经登录了。

 

大致回调处理代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

/**

 * github登录接入回调处理

 *

 * @param request

 * @return

 */

@RequestMapping("/github")

public String githubOAuth(HttpServletRequest request, HttpServletResponse res) {

    try {

        //取得code

        String code = request.getParameter("code");

        //登陆前想要前往的url

        String originUrl = URLDecoder.decode(request.getParameter("state"), "utf-8");

        //请求access token

        String accessTokenUrl = GITHUB_ACCESS_TOKEN_URL_ + code;

        log.info("access token url: " + accessTokenUrl);

        Map<String, String> response = HttpUtil.postRequest(accessTokenUrl, new HashMap<>());

        if (response != null && response.get("access_token") != null) {

            //获取到access token,下面取得用户信息

            Map<String, String> githubUser = HttpUtil.getRequest(GITHUB_USER_INFO_URL_ 

            + response.get("access_token"));

            log.info("user info: " + githubUser);

            UserInfo userInfo = UserInfo.buildFromGithub(githubUser);

            if (!userInfoService.isExistById(userInfo.getId())) {

                userInfoService.insert(userInfo);

            }

            String key =  ......;  //生成cookie

            redisManager.setWithExpireTime(key, userInfo.getId(), SESSION_EXPIRE);

            Cookie cookie = new Cookie(BlogConstant.OAUTH_SESSION_ID, key);

            cookie.setMaxAge(SESSION_EXPIRE);

            cookie.setPath("/");

            res.addCookie(cookie);

        else {

            log.warn("can not get access token., response=" + response);

        }

        return "redirect:"

                + originUrl.substring(originUrl.indexOf("/", originUrl.indexOf("://") + 3));

    catch (Exception e) {

        log.error("error when oauth with github.", e);

    }

    return "redirect:/index";

}

 

第三步:在需要登录的地方引导用户前往github登录

这里是在评论页面上通过jsp来实现的:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

<%--评论区--%>

<div class="remark-div">

    <span class="latest-span"><img src="image/remark.png"/><font

            class="mini-title">&nbsp;&nbsp;所有评论</font></span>

    <div class="clear"></div>

    <hr/>

    <%--未登录--%>

    <c:if test="${userInfo == null}">

        您尚未登录!选择登录方式登录后方可评论~&nbsp;&nbsp;&nbsp;&nbsp;

        <img src="image/github_icon.jpg" alt="github" title="github" class="oauth-login-logo"

             onclick="javascript:window.location.href = 

             'https://github.com/login/oauth/authorize?client_id=*****&redirect_uri=****&state='

             +UrlEncode(window.location.href);"/>

    </c:if>

    <%--已经登录,可以发表评论--%>

    <c:if test="${userInfo != null}">

        - <img src="${userInfo.iconUrl }" class="user-icon"

               onclick="javascript:window.location.href='${userInfo._3rdPartyHomeUrl }';"/>

        <span class="username">&nbsp;&nbsp;${userInfo.username }</span>

        <span style="color: gray;font-size: small;">&nbsp;&nbsp;&nbsp;&nbsp;【您已登录,欢迎评论~】

            <a style="cursor: pointer;text-decoration: underline;color: blue;"

               onclick="javascript:window.location.href='/oauth/logout?originUrl='

               +UrlEncode(window.location.href);">退出登录</a>

        </span>

        <br/><br/>

        <textarea id="remark-text"></textarea>

        <br/>

        <button type="button" class="remark-btn" onclick="publishRemark()">发表评论</button>

    </c:if>

    <hr/>

    ......

 

以上就基本完成了github登录的接入,过程中的接口细节需要完全遵循文档,下面几个是过程中需要参考的文档:

https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps 

https://developer.github.com/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/ 

https://developer.github.com/v3/ 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值