主頁 > 後端開發 > 如何使用GitHub帳戶實作社交登錄?

如何使用GitHub帳戶實作社交登錄?

2022-04-07 03:59:05 後端開發

我的雇主要求我使用用戶的 GitHub 帳戶為我們的 Web 應用程式實施登錄系統。我在網上環顧四周,但我無法找到關于如何使用 GitHub 帳戶(而不是 Facebook 或 Google 帳戶)進行此操作的明確解釋。

uj5u.com熱心網友回復:

我剛剛花了大約一周的時間來弄清楚如何做到這一點,所以我想我會寫一個解釋來節省未來開發人員的時間。

簡短的(呃)答案

您需要遵循GitHub 檔案(“授權 OAuth 應用程式”)中的如何使用 GitHub 帳戶實作社交登錄?

  • The slide title is "OIDC Authorization Code Flow" but the same flow is used for a non-OIDC OAuth 2.0 authorization code flow, with the only difference being that step 10 doesn't return an ID token, just the access token and refresh token.
  • The fact that step 11 is highlighted in green isn't significant; it's just the step the presenter wanted to highlight for this particular slide.
  • The graph shows the "Identity Provider" and "Resource Server" as separate entities, which might be confusing. In our case they're both GitHub's API; the "Identity Provider" is the part of GitHub's API that gets us an access token, and the "Resource Server" is the part of GitHub's API that we can send the access token to to take actions on behalf of the user (e.g. asking about their profile).
  • Source: Introduction to OAuth 2.0 and OpenID Connect (PowerPoint slides) - PragmaticWebSecurity.com
  • OpenID Connect (OIDC)
    • Again, GitHub doesn't seem to support this, but it's mentioned a lot online, so you may be curious to know what's going on here / what problem it solves / why GitHub doesn't support it.
    • The best explanation I've seen for why OpenID Connect was introduced and why it would be preferred over plain OAuth 2.0 for authentication is my own summary of a 2012 ThreadSafe blog post: Why use OpenID Connect instead of plain OAuth2?.
      • The short answer is that before OIDC existed, pure-frontend social login JavaScript libraries (like Facebook's) were using plain OAuth 2.0, but this method was open to an exploit where a malicious web app could have a user sign into their site (for example, using Facebook login) and then use the generated (Facebook) access token to impersonate that user on any other site that accepted that (Facebook) access token as a method of authentication. OIDC prevents that exploit.
        • This particular exploit is what people are referring to when they say "OAuth 2.0 is an authorization protocol, not an authentication protocol...OAuth says absolutely nothing about the user, nor does it say how the user proved their presence or even if they're still there.", which I saw mentioned over and over again while doing research on how to use OAuth 2.0 to implement social login, and which had me initially thinking that I needed to use OpenID Connect.
      • But GitHub doesn't have a pure-frontend social login JavaScript library, so it doesn't need to support OpenID Connect to address that exploit. You just need to make sure your app's back-end is keeping track of which GitHub access tokens it has generated rather than just trusting any valid GitHub access token it receives.
  • While doing research I came across HelloJS and wondered if I could use it to implement social login. From what I can tell, the answer is "not securely".
    • The first thing to understand is that when you use HelloJS, it is using the same authentication code flow I describe above, except HelloJS has its own back-end ("proxy") server set up to allow you to skip writing the back-end code normally needed to implement this flow, and the HelloJS front-end library allows you to skip writing all the front-end code normally needed.
    • The problem with using HelloJS for social login is the back-end server/proxy part: there seems to be no way to prevent the kind of attack that OpenID Connect was created to prevent: the end result of using HelloJS seems to be a GitHub access token, and there seems to be no way for your app's back-end to tell whether that access token was created by the user trying to log into your app or if it was created when the user was logging into some other malicious app (which is then using that access token to send requests to your app, impersonating the user).
      • If your app doesn't use a back-end then you could be fine, but most apps do rely on a back-end to store user-specific data that should only be accessible to that user.
      • You could get around this problem if you were able to query the proxy server to double-check which access tokens it had generated, but HelloJS doesn't seem to have a way to do this out-of-the-box, and if you decide to create your own proxy server so that you can do this, you seem to be ending up in a more-complicated situation than if you'd just avoided HelloJS from the beginning.
    • HelloJS instead seems to be intended for situations where your front-end just wants to query the GitHub API on behalf of the user to get information about their account, like their user details or their list of repositories, with no expectation that your back-end will be using the user's GitHub access token as a method for that user to access their private information on your back-end.
  • To implement the "web application flow" I used the following article as a reference, although it didn't perfectly map to what I needed to do with GitHub: OpenID Connect Client by Example - Codeburst.io
    • Keep in mind that this guide is for implementing the OpenID Connect authentication flow, which is similar-to-but-not-the-same-as the flow we need to use for GitHub.
    • The code here was especially helpful for getting my front-end code working properly.
    • GitHub does not allow for the use of a "nonce" as described in this guide, because that is a feature specific to (some implementations of?) OpenID Connect, and GitHub's API does not support the use of a nonce in the same way that Google's API does.
  • To implement the "device flow" I used the following article as inspiration: Using the OAuth 2.0 device flow to authenticate users in desktop apps
    • The key quote is this: "Basically, when you need to authenticate, the device will display a URL and a code (it could also display a QR code to avoid having to copy the URL), and start polling the identity provider to ask if authentication is complete. You navigate to the URL in the browser on your phone or computer, log in when prompted to, and enter the code. When you’re done, the next time the device polls the IdP, it will receive a token: the flow is complete."
  • Example code

    • The app I'm working on uses Vue Quasar TypeScript on the front-end, and Python aiohttp on the back-end. Obviously you may not be able to use the code directly, but hopefully using it as a reference will give you enough of an idea of what the finished product should look like that you can more-quickly get your own code working.
    • Because of Stack Overflow's post length limits, I can't include the code in the body of this answer, so instead I'm linking the code in individual GitHub Gists.
    • App.vue
      • This is the 'parent component' which the entire front-end application is contained within. It has code that handles the situation during the "web application flow" where the user has been redirected by GitHub back to our application after authorizing our application. It takes the authorization code from the URL query parameters and sends it to our application's back-end, which in turn sends the authorization code to GitHub in exchange for the access token and refresh token.
    • axios.ts
      • This is most of the code from axios.ts. This is where I put the code that adds the GitHub access token to all requests to our app's back-end (if the front-end finds such a token in localStorage), as well as the code that looks at any responses from our app's back-end to see if the access token has been refreshed.
    • auth.py
      • This is the back-end file that contains all the routes used during the login process for both the "web application flow" and the "device flow". If the route URL contains "oauth" it's for the "web application flow", and if the route URL contains "device" it's for the "device flow"; I was just following GitHub's example there.
    • middleware.py
      • This is the back-end file that contains the middleware function that evaluates all incoming requests to see if the presented GitHub access token is one in our app's database, and hasn't yet expired. The code for refreshing the access token is in this file.
    • Login.vue
      • This is the front-end component that displays the "Login page". It has code for both the "web application flow" as well as the "device flow".

    Summary of the two login flows as implemented in my application:

    The web application flow
    1. The user goes to http://mywebsite.com/
    2. The front-end code checks whether there's an access_token localStorage variable (which would indicate the user has already logged in), and doesn't find one, so it redirects the user to the /login route.
      • See App.vue:mounted() and App.vue:watch:authenticated()
    3. At the Login page/view, the user clicks the "Sign in with GitHub" button.
    4. The front-end sets a random state localStorage variable, then redirects the user to GitHub's OAuth app authorization page with our app's client ID and the random state variable as URL query parameters.
      • See Login.vue:redirectUserToGitHubWebAppFlowLoginLink()
    5. The user signs into GitHub (if they're not already signed in), authorizes our application, and is redirected back to http://mywebsite.com/ with an authentication code and the state variable as URL query parameters.
    6. The app is looking for those URL query parameters every time it loads, and when it sees them, it makes sure the state variable matches what it stored in localStorage, and if so, it POSTs the authorization code to our back-end.
      • See App.vue:mounted() and App.vue:sendTheBackendTheAuthorizationCodeFromGitHub()
    7. Our app's back-end receives the POSTed authorization code and then very quickly:
      • Note: the steps below are in auth.py:get_web_app_flow_access_token_and_refresh_token()
      1. It sends the authorization code to GitHub in exchange for the access token and refresh token (as well as their expiration times).
      2. It uses the access token to query GitHub's "/user" endpoint to get the user's GitHub username, email address, and name.
      3. It looks in our database to see if we have a user with the retrieved GitHub username, and if not, creates one.
      4. It creates a new "oauth_tokens" database record for the newly-retrieved access tokens and associates it with the user record.
      5. Finally, it sends the access token to the front-end in the response to the front-end's request.
    8. The front-end receives the response, sets an access_token variable in localStorage, and sets an authenticated Vue variable to true, which the app is constantly watching out for, and which triggers the front-end to redirect the user from the "login" view to the "app" view (i.e. the part of the app that requires the user to be authenticated).
      • See App.vue:sendTheBackendTheAuthorizationCodeFromGitHub() and App.vue:watch:authenticated()
    The device flow
    1. The user goes to http://mywebsite.com/
    2. The front-end code checks whether there's an access_token localStorage variable (which would indicate the user has already logged in), and doesn't find one, so it redirects the user to the /login route.
      • See App.vue:mounted() and App.vue:watch:authenticated()
    3. At the Login page/view, the user clicks the "Sign in with GitHub" button.
    4. The front-end sends a request to our app's back-end asking for the user code that the user will enter while signed into their GitHub account.
      • See Login.vue:startTheDeviceLoginFlow()
    5. The back-end receives this request and:
      • See auth.py:get_device_flow_user_code()
      1. Sends a request to GitHub asking for a new user_code.
      2. Creates an asynchronous task polling GitHub to see if the user has entered the user_code yet.
      3. Sends the user a response with the user_code and device_code that it got from GitHub.
    6. The front-end receives the response from our app's back-end and:
      1. It stores the user_code and device_code in Vue variables.
        • See Login.vue:startTheDeviceLoginFlow()
        • The device_code is also saved to localStorage so that if the user closes the browser window that has the "log in" page open and then opens up a new one, they won't need to restart the login process.
      2. It displays the user_code to the user.
        • See Login.vue in the template code block starting <div v-if="deviceFlowUserCode">
      3. It shows a button that will open the GitHub URL where the user can enter the user_code (it will open the page in a new tab).
      4. It shows a QR code that links to the same GitHub link, so that if the user is using the application on a computer and wants to enter the code on their phone, they can do that.
      5. The app uses the received device_code to set a deviceFlowDeviceCode variable. A separate part of the code in the app is constantly checking to see if that variable has been set, and when it sees that it has, it begins polling the back-end to see if the back-end has received the access_token yet from GitHub.
        • See Login.vue:watch:deviceFlowDeviceCode() and Login.vue:repeatedlyPollTheBackEndForTheAccessTokenGivenTheDeviceCode()
    7. The user either clicks the aforementioned button or scans the QR code with their phone, and enters the user code at https://github.com/login/device while logged into their GitHub account, either on the same device this application is running on or some other device (like their phone).
    8. The back-end, while polling GitHub every few seconds as previously mentioned, receives the access_token and refresh_token, and as mentioned while describing the "web app flow", sends a request to GitHub's "/user" endpoint to get user data, then gets or creates a user db record, and then creates a new oauth_tokens db record.
      • See auth.py:_repeatedly_poll_github_to_check_if_the_user_has_entered_their_code()
    9. The front-end, while polling our application's back-end every few seconds, finally receives a response from the back-end with the access_token, sets an access_token variable in localStorage, redirects the user to the "app" view (i.e. the part of the app that requires the user to be authenticated).
      • See Login.vue:repeatedlyPollTheBackEndForTheAccessTokenGivenTheDeviceCode()

    轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/456837.html

    標籤:验证 github oauth-2.0 github-api

    上一篇:GitHub操作的作業流檔案無效

    下一篇:CSS和影像在GitHub頁面上不起作用

    標籤雲
    其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

    熱門瀏覽
    • 【C++】Microsoft C++、C 和匯編程式檔案

      ......

      uj5u.com 2020-09-10 00:57:23 more
    • 例外宣告

      相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

      uj5u.com 2020-09-10 00:57:27 more
    • Codeforces 1400E Clear the Multiset(貪心 + 分治)

      鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

      uj5u.com 2020-09-10 00:57:30 more
    • UVA11610 【Reverse Prime】

      本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

      uj5u.com 2020-09-10 00:57:36 more
    • 統計區間素數數量

      1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

      uj5u.com 2020-09-10 00:57:47 more
    • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

      1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

      uj5u.com 2020-09-10 00:58:04 more
    • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

      1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

      uj5u.com 2020-09-10 00:59:11 more
    • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

      1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

      uj5u.com 2020-09-10 01:00:19 more
    • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

      今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

      uj5u.com 2020-09-10 01:00:22 more
    • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

      眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

      uj5u.com 2020-09-10 01:00:41 more
    最新发布
    • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

      Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

      uj5u.com 2023-04-20 07:24:10 more
    • Java的值傳遞和參考傳遞

      值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

      uj5u.com 2023-04-20 07:24:04 more
    • [2]SpinalHDL教程——Scala簡單入門

      第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

      uj5u.com 2023-04-20 07:23:58 more
    • 理解函式指標和回呼函式

      理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

      uj5u.com 2023-04-20 07:23:52 more
    • Django筆記二十五之資料庫函式之日期函式

      本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

      uj5u.com 2023-04-20 07:23:45 more
    • 一天吃透JVM面試八股文

      什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

      uj5u.com 2023-04-20 07:23:31 more
    • 使用Java接入小程式訂閱訊息!

      更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

      uj5u.com 2023-04-20 07:22:59 more
    • java -- 緩沖流、轉換流、序列化流

      緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

      uj5u.com 2023-04-20 07:22:49 more
    • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

      老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

      uj5u.com 2023-04-20 07:22:42 more
    • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

      教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

      uj5u.com 2023-04-20 07:22:35 more