沒錯,用三方 Github 做授權(quán)登錄就是這么簡單!
本文轉(zhuǎn)載自微信公眾號「程序員內(nèi)點事」,作者程序員內(nèi)點事 。轉(zhuǎn)載本文請聯(lián)系程序員內(nèi)點事公眾號。
最近在做自己的開源項目(fire),Springboot + vue 的前后端分離框架才搭建完,剛開始做登錄功能,做著做著覺得普通賬戶密碼登錄太簡單了沒啥意思,思來想去為顯得逼格高一點,決定再加上 GitHub授權(quán) 和 人臉識別等多種登錄方式。
在這里插入圖片描述
而GitHub授權(quán)登錄正好用到了OAuth2.0中最復(fù)雜的授權(quán)碼模式,正好拿我這個案例給大家分享一下OAuth2.0的授權(quán)過程,我把項目已經(jīng)部署到云服務(wù),文末有預(yù)覽地址,小伙伴們可以體驗一下,后續(xù)項目功能會持續(xù)更新。
一、授權(quán)流程
在具體做GitHub授權(quán)登錄之前,咱們再簡單回顧一下OAuth2.0授權(quán)碼模式的授權(quán)流程,如果 fire 網(wǎng)站允許 用GitHub 賬號登錄,流程大致如下圖。
在這里插入圖片描述
用戶想用GitHub 賬號去登錄 fire 網(wǎng)站:
- fire 網(wǎng)站先讓用戶跳轉(zhuǎn)到 GitHub 進行授權(quán),會彈出一個授權(quán)框。
- 用戶同意后,GitHub 會根據(jù)redirect_uri 重定向回 fire 網(wǎng)站,同時返回一個授權(quán)碼code。
- fire 網(wǎng)站使用授權(quán)碼和客戶端密匙client_secret,向 GitHub 請求令牌token,檢驗通過返回令牌。
- 最后fire 網(wǎng)站向GitHub 請求數(shù)據(jù),每次調(diào)用 GitHub 的 API 都要帶上令牌。
二、身份注冊
梳理完授權(quán)邏輯,接下來我們還有一些準(zhǔn)備工作。
要想得到一個網(wǎng)站的OAuth授權(quán),必須要到它的網(wǎng)站進行身份注冊,拿到應(yīng)用的身份識別碼 ClientID 和 ClientSecret。
注冊 傳送門 https://github.com/settings/applications/1334665,有幾個必填項。
- Application name:我們的應(yīng)用名;
- Homepage URL:應(yīng)用主頁鏈接;
- Authorization callback URL:這個是github 回調(diào)我們項目的地址,用來獲取授權(quán)碼和令牌。
提交后會看到就可以看到客戶端ClientID 和客戶端密匙ClientSecret,到這我們的準(zhǔn)備工作就完事了。
在這里插入圖片描述
三、授權(quán)開發(fā)
1、獲取授權(quán)碼
為了更好的看效果,獲取授權(quán)碼我處理的比較粗暴,直接在JS里拼裝好了授權(quán)鏈接,但實際工作開發(fā)中一定要考慮到安全問題。
- https://github.com/login/oauth/authorize?
- client_id=ad41c05c211421c659db&
- redirect_uri=http://47.93.6.5:8080/authorize/redirect
前端 vue 的邏輯也非常簡單,只需要 window.location.href 重定向一下。
- <script>
- export default {
- methods: {
- loginByGithub: function () {
- window.location.href = 'https://github.com/login/oauth/authorize?client_id=ad41c05c211421c659db&redirect_uri=http://47.93.6.5:8080/authorize/redirect'
- }
- }
- }
- </script>
請求后會提示讓我們授權(quán),同意授權(quán)后會重定向到authorize/redirect,并攜帶授權(quán)碼code;如果之前已經(jīng)同意過,會跳過這一步直接回調(diào)。
在這里插入圖片描述
2、獲取令牌
授權(quán)后緊接著就要回調(diào) fire 網(wǎng)站接口,拿到授權(quán)碼以后拼裝獲取令牌 access_token的請求鏈接,這時會用到客戶端密匙client_secret。
- https://github.com/login/oauth/access_token?
- client_id=${clientID}&
- client_secret=${clientSecret}&
- code=${requestToken}
access_token 會作為請求響應(yīng)返回,結(jié)果是個串字符,需要我們截取一下。
- access_token=4dc43c2f43b773c327f97acf5dd66b147db9259c&scope=&token_type=bearer
有了令牌以后開始獲取用戶信息,在 API 中要帶上access_token。
- https://api.github.com/user?access_token=4dc43c2f43b773c327f97acf5dd66b147db9259c
返回的用戶信息是 JSON 數(shù)據(jù)格式,如果想把數(shù)據(jù)傳遞給前端,可以通過 url 重定向到前端頁面,將數(shù)據(jù)以參數(shù)的方式傳遞。
- {
- "login": "chengxy-nds",
- "id": 12745094,
- "node_id": "",
- "avatar_url": "https://avatars3.githubusercontent.com/u/12745094?v=4",
- "gravatar_id": "",
- "url": "https://api.github.com/users/chengxy-nds",
- "html_url": "https://github.com/chengxy-nds",
- "followers_url": "https://api.github.com/users/chengxy-nds/followers",
- "following_url": "https://api.github.com/users/chengxy-nds/following{/other_user}",
- "gists_url": "https://api.github.com/users/chengxy-nds/gists{/gist_id}",
- "starred_url": "https://api.github.com/users/chengxy-nds/starred{/owner}{/repo}",
- "subscriptions_url": "https://api.github.com/users/chengxy-nds/subscriptions",
- "organizations_url": "https://api.github.com/users/chengxy-nds/orgs",
- "repos_url": "https://api.github.com/users/chengxy-nds/repos",
- "events_url": "https://api.github.com/users/chengxy-nds/events{/privacy}",
- "received_events_url": "https://api.github.com/users/chengxy-nds/received_events",
- "type": "",
- "site_admin": false,
- "name": "程序員內(nèi)點事",
- "company": null,
- "blog": "",
- "location": null,
- "email": "",
- "hireable": null,
- "bio": null,
- "twitter_username": null,
- "public_repos": 7,
- "public_gists": 0,
- "followers": 14,
- "following": 0,
- "created_at": "2015-06-04T09:22:44Z",
- "updated_at": "2020-07-13T06:08:57Z"
- }
下邊是 GitHub 回調(diào)我們 fire網(wǎng)站后端處理流程的部分代碼,寫的比較糙,后續(xù)繼續(xù)優(yōu)化吧!
- /**
- * @param code
- * @author xiaofu
- * @description 授權(quán)回調(diào)
- * @date 2020/7/10 15:42
- */
- @RequestMapping("/authorize/redirect")
- public ModelAndView authorize(@NotEmpty String code) {
- log.info("授權(quán)碼code: {}", code);
- /**
- * 重新到前端主頁
- */
- String redirectHome = "http://47.93.6.5/home";
- try {
- /**
- * 1、拼裝獲取accessToken url
- */
- String accessTokenUrl = gitHubProperties.getAccesstokenUrl()
- .replace("clientId", gitHubProperties.getClientId())
- .replace("clientSecret", gitHubProperties.getClientSecret())
- .replace("authorize_code", code);
- /**
- * 返回結(jié)果中直接返回token
- */
- String result = OkHttpClientUtil.sendByGetUrl(accessTokenUrl);
- log.info(" 請求 token 結(jié)果:{}", result);
- String accessToken = null;
- Pattern p = Pattern.compile("=(\\w+)&");
- Matcher m = p.matcher(result);
- while (m.find()) {
- accessToken = m.group(1);
- log.info("令牌token:{}", m.group(1));
- break;
- }
- /**
- * 成功獲取token后,開始請求用戶信息
- */
- String userInfoUrl = gitHubProperties.getUserUrl().replace("accessToken", accessToken);
- String userResult = OkHttpClientUtil.sendByGetUrl(userInfoUrl);
- log.info("用戶信息:{}", userResult);
- UserInfo userInfo = JSON.parseObject(userResult, UserInfo.class);
- redirectHome += "?name=" + userInfo.getName();
- } catch (Exception e) {
- log.error("授權(quán)回調(diào)異常={}", e);
- }
- return new ModelAndView(new RedirectView(redirectHome));
- }
最后我們動圖看一下整體的授權(quán)流程,由于GitHub的訪問速度比較慢,偶爾會有請求超時的現(xiàn)象。
在這里插入圖片描述
線上預(yù)覽地址:http://47.93.6.5/login ,歡迎體驗~
項目 GitHub 地址:https://github.com/chengxy-nds/fire.git
總結(jié)
從整個GitHub授權(quán)登錄的過程來看,OAuth2.0的授權(quán)碼模式還是比較簡單的,搞懂了一個GitHub的登錄,像微信、圍脖其他三方登錄也就都會了,完全是大同小異的東西,感興趣的同學(xué)可以試一試。