π OAuth 2.0 client for GitHub
Give a βοΈ if this project helped you!
https://oauth-client-github-demo.vercel.app/
π‘ Source code of this app in demo/ directory.
npm install oauth-client-github
// server.js
const oauthClientGitHub = require("oauth-client-github");
const githubAuth = oauthClientGitHub.init({
client_id: "",
client_secret: "",
redirect_uri: "<host>/auth/callback",
scope: "", // user, repo, gist, notifications, read:org, etc.
});
app.get("/auth", async (req, res) => {
const state = req.headers.referer;
const url = await githubAuth.buildTemporaryTokenUrl({ state });
// Redirect to GitHub OAuth page to authorize a user
res.redirect(url);
});
app.get("/auth/callback", async (req, res) => {
const { code, state } = req.query;
const response = await githubAuth.requestAccessToken({ code });
// Create a cookie to use it on the client-side
res.cookie("token", response.access_token);
res.redirect(state ? String(state) : "/");
});
// client.js
const access_token = document.cookie.split("=")[1];
const response = await fetch("https://api.github.com/user", {
headers: {
Authorization: `Bearer ${access_token}`,
},
});
const user = await response.json();
console.log({ user }); // A user with private data! π
Sequence diagram with the OAuth 2.0 flow for GitHub is defined in docs/ directory.
- Open a page: https://github.com/settings/developers and click on the "New OAuth App"
- Fill the form:
- Application name (required)
- eg.
oauth-client-github
- TIP: it will be visible only for you
- eg.
- Homepage URL (required)
- eg.
https://example.com
- TIP: it will be visible only for you
- eg.
- Application description (optional)
- Authorization callback URL (required)
- eg.
http://localhost:3000/auth/callback
- TIP: you need to put real URL to your app
β οΈ This field will be cross-checked with your paramredirect_uri
- eg.
- Enable Device Flow (optional)
- Generate a new client secret by clicking on the "Generate a new client secret"
- Copy secret and save to config file (like
.env
):- Client ID
- Client Secret
client_id
- GitHub App Client IDclient_secret
- GitHub App Client Secretredirect_uri
- URL to redirect after authorizationscope
- List of scopes separated by commastate
- Random string to prevent CSRF attacks (optional)- Or it could be a referer to redirect user to the same page after authorization
code
- Temporary code to exchange to the access tokenaccess_token
- Access token to make requests to GitHub API
# to rebuild dist/ & types/
npm run watch # or `npm run build` to build once
# to rebuild demo/dist/
cd demo/
npm run dev
The MIT License @ 2024