作為一名開發人員,身份驗證是我最尊重的事情之一;根據我進行身份驗證(也許是基礎級別)的經驗,我總是為一件事或另一件事而苦苦掙扎,尤其是當我必須整合OAuth 時。
在為 jargons.dev 進行此工作之前,我最近一次進行 Auth 的經驗是在 Hearts 上整合了 GitHub OAuth。
所以是的!我在為jargons.dev 做這件事時也遇到了(傳統的?)困難;但老實說,這只是因為設置(即技術)方面的差異- 我在Hearts 上的經驗是將GitHub OAuth 與NextJS 中的伺服器操作集成,同時在jargons.dev 上,我正在將GitHub OAuth 與Astro 集成。
正如我目前所寫,身份驗證系統已經經歷了3 次迭代,併計劃進行更多迭代(下一次迭代的詳細信息請參見本期#30);由於一些未發現的限制,這些幾週的開發迭代已經實現了改進或重構了一兩件事。
此迭代在基本身份驗證功能中實現,允許啟動 GitHub OAuth 流程,響應處理將身份驗證代碼交換為我們安全存儲在用戶 cookie 上的 accessToken。
這次迭代中值得一提的重要變化是
我實現了第一個操作(與新的實驗性Astro 伺服器操作無關,我在宣布之前很久就完成了這個?) - 這是我剛剛編造的一個術語,用於調用在伺服器端運行的函數Astro“在頁面載入之前”,你應該知道它的命名約定:doAction,以及它以astroGlobal 物件作為唯一參數的風格,通常是傳回回應物件的非同步函數。
doAuth - 此操作集成在我希望保護的任何頁面上,它檢查cookie 中是否存在訪問令牌; — 如果存在:它將其交換為用戶數據,並返回一個布林值isAuthed 以確認受保護頁面的身份驗證; — 如果未找到令牌:它會檢查url 搜尋參數中是否存在oath 流授權程式碼,將其交換為存取權杖(透過呼叫api/github/oauth/authorize 路由)並將其安全性儲存到cookie,然後使用適當地設定cookie;現在,如果cookie 中沒有找到accessToken 並且url 搜尋參數中沒有授權碼,則傳回值isAuthed 為false,並將在受保護頁面上使用它來重定向到登入頁面。
const { isAuthed, authedData: userData } = await doAuth(Astro); if (!isAuthed) return redirect(`/login?return_to=${pathname}`);
This Pull request implement the authentication feature in the project; using the github oauth, our primary goal is to get and hold users github accessToken in cookies for performing specific functionality. It is important to state that this feature does not take store this user's accessToken to any remote server, this token and any other information that was retrieved using the token are all saved securely on the users' end through usage of cookies.
Implemented the github oauth callback handler at /api/github/oauth/callback - this handler's main functionality is to receive github's authorization code and state to perform either of the following operations
Implemented the github oauth authorization handler at /api/github/oauth/authorization - this handler is a helper that primarily exchanges the authorization code for tokens and returns it in a json object.
Created a singleton instance of our github app at lib/octokit/app
Added a new crypto util function which provides encrypt and decrypt helper function has exports; it is intended to be used for securing the users related cookies
Implemented the doAuth action function - this function take the Astro global object as argument and performs the operations stated below
/**
* Authentication action with GitHub OAuth
* @param {import("astro").AstroGlobal} astroGlobal
*/
export default async function doAuth(astroGlobal) {
const { url: { searchParams }, cookies } = astroGlobal;
const code = searchParams.get("code");
const accessToken = cookies.get("jargons.dev:token", {
decode: value => decrypt(value)
});
/**
* Generate OAuth Url to start authorization flow
* @todo make the `parsedState` data more predictable (order by path, redirect)
* @todo improvement: store `state` in cookie for later retrieval in `github/oauth/callback` handler for cleaner url
* @param {{ path?: string, redirect?: boolean }} state
*/
function getAuthUrl(state) {
const parsedState = String(Object.keys(state).map(key => key + ":" + state[key]).join("|"));
const { url } = app.oauth.getWebFlowAuthorizationUrl({
state: parsedState
});
return url;
}
try {
if (!accessToken && code) {
const response = await GET(astroGlobal);
const responseData = await response.json();
if (responseData.accessToken && responseData.refreshToken) {
cookies.set("jargons.dev:token", responseData.accessToken, {
expires: resolveCookieExpiryDate(responseData.expiresIn),
encode: value => encrypt(value)
});
cookies.set("jargons.dev:refresh-token", responseData.refreshToken, {
expires: resolveCookieExpiryDate(responseData.refreshTokenExpiresIn),
encode: value => encrypt(value)
});
}
}
const userOctokit = await app.oauth.getUserOctokit({ token: accessToken.value });
const { data } = await userOctokit.request("GET /user");
return {
getAuthUrl,
isAuthed: true,
authedData: data
}
} catch (error) {
return {
getAuthUrl,
isAuthed: false,
authedData: null
}
}
}
Added the login page which stands as place where where unauthorised users witll be redirected to; this page integrates the doAuth action, destruing out the getAuthUrl helper and the isAuthed property, it uses them as follows
const { getAuthUrl, isAuthed } = await doAuth(Astro);
if (isAuthed) return redirect(searchParams.get("redirect"));
const authUrl = getAuthUrl({
path: searchParams.get("redirect"),
redirect: true
});
// pages/sandbox.astro
---
import BaseLayout from "../layouts/base.astro";
import doAuth from "../lib/actions/do-auth.js";
import { $userData } from "../stores/user.js";
const { url: { pathname }, redirect } = Astro;
const { isAuthed, authedData } = await doAuth(Astro);
if (!isAuthed) return redirect(`/login?redirect=<span class="pl-s1"><span class="pl-kos">${pathname}</span>`</span>);
$userData.set(authedData);
---
11cef86d50b82c68655376cb62f0db5b
e33cc9d786368fb494b726688270e59a
713e9867a88cfb8c49f3f463c33c78a3
3f1d768d1c2bece0763d63bdace7515a
e388a4556c0f65e1904146cc1a846beeHello, { authedData.login }94b3e26ee717c64999d7867364b1b4a3
16b28748ea4df4d9c2150843fecfba68
07ebbc2b3735b6cb0330715d08d2749e
a7404faa8989ab176c7e812b70808e66
Explainer
screencast-bpconcjcammlapcogcnnelfmaeghhagj-2024.03.29-20_36_15.webm
This iteration implements improvements by making making the parsedState derived from the getAuthUrl function call more predictable removing the chances of an error in the api/github/oauth/callback route; it also renames some terms used in the search params and implements the the encodeURIComponent to make our redirect urls look less weird
See PR:
This PR implements some improvement to mark the second iteration of the auth feature in the project. Follow-up to #8
function getAuthUrl(state) {
let parsedState = "";
if (!isObjectEmpty(state)){
if (state.path) parsedState += `path:<span class="pl-s1"><span class="pl-kos">${state.path}</span>`</span>;
const otherStates = String(Object.keys(state)
.filter(key => key !== "path" && key !== "redirect")
.map(key => key + ":" + state[key]).join("|"));
if (otherStates.length > 0) parsedState += `|<span class="pl-s1"><span class="pl-kos">${otherStates}</span>`</span>;
}
const { url } = app.oauth.getWebFlowAuthorizationUrl({
state: parsedState
});
return url;
}
Resolves #15
由於我在另一個腳本上所做的工作期間出現了某種限制,因此這次迭代重構了「第一次迭代」中實現的大部分部分。
此時我正在編寫“Submit Word”腳本;此腳本利用GitHub API 並創建拉取請求,以將從當前經過身份驗證的用戶的fork 分支所做的更改合併到基礎(jargons.dev) 主分支。當然,這是透過儲存到 cookie 中的使用者存取權令牌來實現的,該令牌在請求標頭中由 SDK(即 Octokit)用作“授權承載令牌”,方便我們與 GitHub API 進行互動。
在測試期間,當我嘗試提交單字腳本時,我遇到了錯誤......
錯誤:整合無法存取資源
...這很快就成為了一個障礙,我諮詢了@gr2m,我們很快就發現了與我的 GitHub 應用程式整合相關的限制。
正如最初所述,GitHub 應用程式使用帶有細粒度令牌的「權限」 - GitHub 出於一些非常好的原因而鼓勵使用的新令牌類型,下面引用的一個是我們在這裡關注的....
GitHub 應用程式提供了對應用程式功能的更多控制。 GitHub 應用程式使用細粒度的權限,而不是 OAuth 應用程式使用的廣泛範圍。例如,如果您的應用程式需要讀取儲存庫的內容,則 OAuth 應用程式將需要儲存庫範圍,這也允許應用程式編輯儲存庫內容和設定。 GitHub 應用程式可以請求對儲存庫內容的唯讀存取權限,這不會讓應用程式執行更多特權操作,例如編輯儲存庫內容或設定。
...這表示當使用「權限」(即細粒度權限)時,使用者必須具有對上游/基礎儲存庫的寫入權限,在本例中是我們的jargons.dev 儲存庫;如GitHub 建立拉取請求文件中所述。
說什麼! ?沒有! ! !
就在那時,我們發現普通的舊作用域正是我們所需要的;為了能夠存取所需的資源,public_repo 範圍就是一切。
為了繼續前進,我必須從“權限”切換到“範圍”,我們在 GitHub 的“OAuth App”中發現了這一點;這是第三次迭代修補的基礎。
因此,本次迭代主要側重於交換GitHub OAuth 集成,同時確保本次迭代中實現的幫助程序/函數/api 類似於GitHub 應用程式提供的幫助程序/函數/api,以減少我要做的更改量跨越整個程式碼庫以感謝新的實現。
GitHub 應用程式很棒,我必須承認,如果我們最終找到錯誤的解決方案:資源無法通過集成錯誤訪問,但創建拉取請求的功能已執行,我仍然會考慮到未來提交單詞腳本是該專案的重要組成部分,因此我們必須確保它有效。
需要指出的是,為了支援功能,我必須做出一些權衡......
解決方法
查看公關:
This Pull request refactors the authentication system, replacing the usage of github-app-oauth with classic github oauth app. This decision was taken because of the limitations discovered using the Pull Request endpoint (implementation in #25); the github-app-oauth uses permissions which requires a user to have write access to the upstream (i.e. write access to atleast pull-requests on our/this project repo) before a pull request can created from their forked repo branch to the main project repo.
This PR goes to implement classis oauth app, which uses scopes and allows user access to create the pull request to upstream repo on the public_repo scope. The changes made in this PR was done to mimic the normal Octokit.App's methods/apis as close as possible to allow compatibility with the implementation in #8 and #28 (or for cases when we revert back to using the github-app-oauth in the future --- maybe we end up finding a solution because honestly I really prefer the github-app-oauth ?).
It is also important to state that this oauth app option doesn't offer a short lived token (hence we only have an accessToken without expiry and No refreshToken), but I have configured the token to expire out of cookie in 8hours; even though we might be getting exactly thesame token back from github after this expires and we re-authorize the flow, I just kinda like that feeling of the cookies expiring after some hours and asking user to re-auth.
octokit - the main octokit instance of the oauth app
/**
* OAuth App's Octokit instance
*/
const octokit = new Octokit({
authStrategy: createOAuthAppAuth,
auth: {
clientId: import.meta.env.GITHUB_OAUTH_APP_CLIENT_ID,
clientSecret: import.meta.env.GITHUB_OAUTH_APP_CLIENT_SECRET
},
});
oauth
getWebFlowAuthorizationUrl - method that generates the oauth flow url
/**
* Generate a Web Flow/OAuth authorization url to start an OAuth flow
* @param {import("@octokit/oauth-authorization-url").OAuthAppOptions} options
* @returns
*/
function getWebFlowAuthorizationUrl({state, scopes = ["public_repo"], ...options }) {
return oauthAuthorizationUrl({
clientId: import.meta.env.GITHUB_OAUTH_APP_CLIENT_ID,
state,
scopes,
...options
});
}
exchangeWebFlowCode - method that exchanges oauth web flow returned code for accessToken; this functionality was extracted from the github/oauth/authorize endpoint to have all auth related function packed in one place
/**
* Exchange Web Flow Authorization `code` for an `access_token`
* @param {string} code
* @returns {Promise4ae3230490577696c575abb709ab983c}
*/
async function exchangeWebFlowCode(code) {
const queryParams = new URLSearchParams();
queryParams.append("code", code);
queryParams.append("client_id", import.meta.env.GITHUB_OAUTH_APP_CLIENT_ID);
queryParams.append("client_secret", import.meta.env.GITHUB_OAUTH_APP_CLIENT_SECRET);
const response = await fetch("https://github.com/login/oauth/access_token", {
method: "POST",
body: queryParams
});
const responseText = await response.text();
const responseData = new URLSearchParams(responseText);
return responseData;
}
getUserOctokit - method that gets an octokit instance of a user.
/**
* Get a User's Octokit instance
* @param {Omit1e4fb368bde7d280f14ef2719604d1ea & { token: string }} options
* @returns {Octokit}
*/
function getUserOctokit({ token, ...options }) {
return new Octokit({
auth: token,
...options
});
};
?
screencast-bpconcjcammlapcogcnnelfmaeghhagj-2024.04.07-07_37_31.webm
以上是建置 jargons.dev [# 身份驗證系統的詳細內容。更多資訊請關注PHP中文網其他相關文章!