没错,用三方 Github 做授权登录就是这么简单!,


本文转载自微信公众号「程序员内点事」,作者程序员内点事 。转载本文请联系程序员内点事公众号。

最近在做自己的开源项目(fire),Springboot + vue 的前后端分离框架才搭建完,刚开始做登录功能,做着做着觉得普通账户密码登录太简单了没啥意思,思来想去为显得逼格高一点,决定再加上 GitHub授权 和 人脸识别等多种登录方式。

在这里插入图片描述

而GitHub授权登录正好用到了OAuth2.0中最复杂的授权码模式,正好拿我这个案例给大家分享一下OAuth2.0的授权过程,我把项目已经部署到云服务,文末有预览地址,小伙伴们可以体验一下,后续项目功能会持续更新。

一、授权流程

在具体做GitHub授权登录之前,咱们再简单回顾一下OAuth2.0授权码模式的授权流程,如果 fire 网站允许 用GitHub 账号登录,流程大致如下图。

在这里插入图片描述

用户想用GitHub 账号去登录 fire 网站:

  • fire 网站先让用户跳转到 GitHub 进行授权,会弹出一个授权框。
  • 用户同意后,GitHub 会根据redirect_uri 重定向回 fire 网站,同时返回一个授权码code。
  • fire 网站使用授权码和客户端密匙client_secret,向 GitHub 请求令牌token,检验通过返回令牌。
  • 最后fire 网站向GitHub 请求数据,每次调用 GitHub 的 API 都要带上令牌。

二、身份注册

梳理完授权逻辑,接下来我们还有一些准备工作。

要想得到一个网站的OAuth授权,必须要到它的网站进行身份注册,拿到应用的身份识别码 ClientID 和 ClientSecret。

注册 传送门 https://github.com/settings/applications/1334665,有几个必填项。

  • Application name:我们的应用名;
  • Homepage URL:应用主页链接;
  • Authorization callback URL:这个是github 回调我们项目的地址,用来获取授权码和令牌。

提交后会看到就可以看到客户端ClientID 和客户端密匙ClientSecret,到这我们的准备工作就完事了。

在这里插入图片描述

三、授权开发

1、获取授权码

为了更好的看效果,获取授权码我处理的比较粗暴,直接在JS里拼装好了授权链接,但实际工作开发中一定要考虑到安全问题。

  1. https://github.com/login/oauth/authorize? 
  2. client_id=ad41c05c211421c659db& 
  3. redirect_uri=http://47.93.6.5:8080/authorize/redirect 

前端 vue 的逻辑也非常简单,只需要 window.location.href 重定向一下。

  1. <script> 
  2. export default { 
  3.   methods: { 
  4.     loginByGithub: function () { 
  5.       window.location.href = 'https://github.com/login/oauth/authorize?client_id=ad41c05c211421c659db&redirect_uri=http://47.93.6.5:8080/authorize/redirect' 
  6.     } 
  7.   } 
  8. </script> 

请求后会提示让我们授权,同意授权后会重定向到authorize/redirect,并携带授权码code;如果之前已经同意过,会跳过这一步直接回调。

在这里插入图片描述

2、获取令牌

授权后紧接着就要回调 fire 网站接口,拿到授权码以后拼装获取令牌 access_token的请求链接,这时会用到客户端密匙client_secret。

  1. https://github.com/login/oauth/access_token?  
  2.     client_id=${clientID}&  
  3.     client_secret=${clientSecret}&  
  4.     code=${requestToken} 

access_token 会作为请求响应返回,结果是个串字符,需要我们截取一下。

  1. access_token=4dc43c2f43b773c327f97acf5dd66b147db9259c&scope=&token_type=bearer 

有了令牌以后开始获取用户信息,在 API 中要带上access_token。

  1. https://api.github.com/user?access_token=4dc43c2f43b773c327f97acf5dd66b147db9259c 

返回的用户信息是 JSON 数据格式,如果想把数据传递给前端,可以通过 url 重定向到前端页面,将数据以参数的方式传递。

  1.     "login": "chengxy-nds", 
  2.     "id": 12745094, 
  3.     "node_id": "", 
  4.     "avatar_url": "https://avatars3.githubusercontent.com/u/12745094?v=4", 
  5.     "gravatar_id": "", 
  6.     "url": "https://api.github.com/users/chengxy-nds", 
  7.     "html_url": "https://github.com/chengxy-nds", 
  8.     "followers_url": "https://api.github.com/users/chengxy-nds/followers", 
  9.     "following_url": "https://api.github.com/users/chengxy-nds/following{/other_user}", 
  10.     "gists_url": "https://api.github.com/users/chengxy-nds/gists{/gist_id}", 
  11.     "starred_url": "https://api.github.com/users/chengxy-nds/starred{/owner}{/repo}", 
  12.     "subscriptions_url": "https://api.github.com/users/chengxy-nds/subscriptions", 
  13.     "organizations_url": "https://api.github.com/users/chengxy-nds/orgs", 
  14.     "repos_url": "https://api.github.com/users/chengxy-nds/repos", 
  15.     "events_url": "https://api.github.com/users/chengxy-nds/events{/privacy}", 
  16.     "received_events_url": "https://api.github.com/users/chengxy-nds/received_events", 
  17.     "type": "", 
  18.     "site_admin": false, 
  19.     "name": "程序员内点事", 
  20.     "company": null, 
  21.     "blog": "", 
  22.     "location": null, 
  23.     "email": "", 
  24.     "hireable": null, 
  25.     "bio": null, 
  26.     "twitter_username": null, 
  27.     "public_repos": 7, 
  28.     "public_gists": 0, 
  29.     "followers": 14, 
  30.     "following": 0, 
  31.     "created_at": "2015-06-04T09:22:44Z", 
  32.     "updated_at": "2020-07-13T06:08:57Z" 

下边是 GitHub 回调我们 fire网站后端处理流程的部分代码,写的比较糙,后续继续优化吧!

  1. /** 
  2.      * @param code 
  3.      * @author xiaofu 
  4.      * @description 授权回调 
  5.      * @date 2020/7/10 15:42 
  6.      */ 
  7.    @RequestMapping("/authorize/redirect") 
  8.     public ModelAndView authorize(@NotEmpty String code) { 
  9.  
  10.         log.info("授权码code: {}", code); 
  11.  
  12.         /** 
  13.          * 重新到前端主页 
  14.          */ 
  15.         String redirectHome = "http://47.93.6.5/home"; 
  16.  
  17.         try { 
  18.             /** 
  19.              * 1、拼装获取accessToken url 
  20.              */ 
  21.             String accessTokenUrl = gitHubProperties.getAccesstokenUrl() 
  22.                     .replace("clientId", gitHubProperties.getClientId()) 
  23.                     .replace("clientSecret", gitHubProperties.getClientSecret()) 
  24.                     .replace("authorize_code", code); 
  25.  
  26.             /** 
  27.              * 返回结果中直接返回token 
  28.              */ 
  29.             String result = OkHttpClientUtil.sendByGetUrl(accessTokenUrl); 
  30.             log.info(" 请求 token 结果:{}", result); 
  31.  
  32.             String accessToken = null; 
  33.             Pattern p = Pattern.compile("=(\\w+)&"); 
  34.             Matcher m = p.matcher(result); 
  35.             while (m.find()) { 
  36.                 accessToken = m.group(1); 
  37.                 log.info("令牌token:{}", m.group(1)); 
  38.                 break; 
  39.             } 
  40.  
  41.             /** 
  42.              * 成功获取token后,开始请求用户信息 
  43.              */ 
  44.             String userInfoUrl = gitHubProperties.getUserUrl().replace("accessToken", accessToken); 
  45.  
  46.             String userResult = OkHttpClientUtil.sendByGetUrl(userInfoUrl); 
  47.  
  48.             log.info("用户信息:{}", userResult); 
  49.  
  50.             UserInfo userInfo = JSON.parseObject(userResult, UserInfo.class); 
  51.  
  52.             redirectHome += "?name=" + userInfo.getName(); 
  53.  
  54.         } catch (Exception e) { 
  55.             log.error("授权回调异常={}", e); 
  56.         } 
  57.         return new ModelAndView(new RedirectView(redirectHome)); 
  58.     } 

最后我们动图看一下整体的授权流程,由于GitHub的访问速度比较慢,偶尔会有请求超时的现象。

在这里插入图片描述

线上预览地址:http://47.93.6.5/login ,欢迎体验~

项目 GitHub 地址:https://github.com/chengxy-nds/fire.git

总结

从整个GitHub授权登录的过程来看,OAuth2.0的授权码模式还是比较简单的,搞懂了一个GitHub的登录,像微信、围脖其他三方登录也就都会了,完全是大同小异的东西,感兴趣的同学可以试一试。

相关内容