Home > Article > Web Front-end > Building jargons.dev [# The Authentication System
As a developer, Authentication is one of the things that I've got the most respect for; In my experience doing authentication (maybe on a basic level), I've always struggled with one thing or the other especially when I've got to integrate OAuth.
Prior to working on this for jargons.dev, my most recent experience doing Auth was on Hearts where I integrated GitHub OAuth.
So yea! I also had my (traditional ?) struggles working on this for jargons.dev too; but honestly this was only because of the differences in setup (i.e. technology) though — My experience on Hearts was integrating GitHub OAuth with Server Actions in NextJS meanwhile on jargons.dev, I'm integrating GitHub OAuth with Astro.
As I currently write, the authentication system has gone through 3 Iterations, with more planned (details on next iteration in this issue #30); these iterations over the weeks of development have implemented improvements or refactored a thing or two due to some uncovered limitation.
This iteration implemented in base authentication functionality that allows initiation of a GitHub OAuth flow, response handling that exchanges the authentication code for an accessToken that we securely store on user's cookies.
The imperative changes worth stating about this iteration is that
I implemented the first action (not related to the new and experimental Astro Server Actions, I done this long before the announcement ?) — this is a term I just made up to call functions that are ran on the server-side of Astro "before the page loads", you shall know it by its naming convension: doAction, and its style of taking the astroGlobal object as the only parameter, it's usually async function that returns a response object.
doAuth - this action integrates on any page I wish to protect, it checks for the presence of an access token in cookie; — if present: it exchanges that for user data, returns a boolean value isAuthed alongside it to confirm authentication for protected page; — if no token is found: it checks the presence of the oath flow authorization code in url search params, exchanges that for access token (by calling the api/github/oauth/authorize route) and saves it secure to cookies, then uses the cookie appropriately; now in cases where no accessToken is found in cookies and no auth code is in url search params, then the returned value isAuthed is false and it will be used on the protected page to redirect to the login page.
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
This iteration refactors the most parts of the implementation in the "First Iteration" because of a certain limitation that surfaced during the work I was doing on another script.
At this point in time I was working on the "Submit Word" script; this script leverages the GitHub API and create a Pull Request to merge changes made from the currently authenticated user's fork branch to the base (jargons.dev) main branch. This ofcourse is made possible by the access token of the user saved to cookies which is used in the request headers as "Authorization Bearer token" by the SDK i.e. Octokit that facilitates our interaction with the GitHub APIs.
During a test moment as I gave the submit word script a whirl, I was met by the error...
Error: Resource not accessible by integration
...this quickly became a blocker and I consulted @gr2m with whom we quickly uncovered the limitation which related to my integrations of GitHub App.
As initially stated, the GitHub App uses "Permissions" with a fine-grained token - a new token type that GitHub encourages for some very good reasons with the below quoted one as one that concerns us here...
GitHub Apps provide more control over what the app can do. Instead of the broad scopes that OAuth apps use, GitHub Apps use fine-grained permissions. For example, if your app needs to read the contents of a repository, an OAuth app would require the repo scope, which would also let the app edit the repository contents and settings. A GitHub App can request read-only access to repository contents, which will not let the app take more privileged actions like editing the repository contents or settings.
...this means that when using "Permissions" (i.e. fine-grained permissions), a user must have write access to the upstream/base repository which in this case is our jargons.dev repository; as stated in the GitHub Create a Pull Request docs.
Say what!? Nope!!!
It was at that point that we found plain old scope to be exactly what we need; In order to be able to access the required resource, the public_repo scope was everything.
In order to move forward, I had to switch from "permissions" to "scope" and where we found that was in the GitHub's "OAuth App"; this was the basis on which the third iteration was patched.
So this iteration mainly focused on exchanging the GitHub OAuth integration, also ensuring that the implemented helpers/functions/api in this iteration resemble the ones that was made available by the GitHub App to reduces the amount of changes I was going to make across the entire codebase in acknowledgement of the new implementation.
GitHub App is great, I must acknowledge that I still have it in my mind for the future if we end-up finding a solution to the Error: Resource not accessible by integration error, but the functionality to create a Pull Request performed by the submit-word script is an imperative part of the project, so you bet we gotta make sure it works.
It's important to state that there was some trade-offs that I had to settle for in favor of the functionality...
The Workarounds
See PR:
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
The above is the detailed content of Building jargons.dev [# The Authentication System. For more information, please follow other related articles on the PHP Chinese website!