oauth-client-github
v1.0.5
Published
๐ OAuth 2.0 client for GitHub
Downloads
16
Maintainers
Readme
oauth-client-github
๐ OAuth 2.0 client for GitHub
Give a โญ๏ธ if this project helped you!
Preview ๐
https://oauth-client-github-demo.vercel.app/
๐ก Source code of this app in demo/ directory.
Installation
npm install oauth-client-github
Usage
// 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! ๐
Specification
Sequence diagram with the OAuth 2.0 flow for GitHub is defined in docs/ directory.
Prerequisites: Create new OAuth App
- 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 param
redirect_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
Parameters
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
Development
# to rebuild dist/ & types/
npm run watch # or `npm run build` to build once
# to rebuild demo/dist/
cd demo/
npm run dev
Resources
License
The MIT License @ 2024