Our great sponsors
-
node-oauth2-server
Complete, compliant and well tested module for implementing an OAuth2 Server/Provider with express in node.js
-
WorkOS
The modern identity platform for B2B SaaS. The APIs are flexible and easy-to-use, supporting authentication, user identity, and complex enterprise features like SSO and SCIM provisioning.
-
InfluxDB
Power Real-Time Data Analytics at Scale. Get real-time insights from all types of time series data with InfluxDB. Ingest, query, and analyze billions of data points in real-time with unbounded cardinality.
It's important to know that this far, although you can perfectly build your OAuth2 server from scratch using frameworks, such as the node-oauth2-server, we'll make use of GitHub's capabilities for the sake of simplicity.
So, let's create a new application by clicking this link. Make sure to fill in all the fields, as shown in the image below:
const express = require("express"); const axios = require("axios"); var cors = require("cors"); const CLIENT_ID = ""; const CLIENT_SECRET = ""; const GITHUB_URL = "https://github.com/login/oauth/access_token"; const app = express(); app.use(cors({ credentials: true, origin: true })); app.get("/oauth/redirect", (req, res) => { axios({ method: "POST", url: `${GITHUB_URL}?client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}&code=${req.query.code}`, headers: { Accept: "application/json", }, }).then((response) => { res.redirect( `http://localhost:3000?access_token=${response.data.access_token}` ); }); }); const PORT = 8080; app.listen(PORT, () => { console.log(`Listening at port ${PORT}`); });
For this article, we'll be using Node.js, and Yarn as the default package manager. Node is on version v12.21.0 to be specific. However, most of the versions higher than 10 should work just fine.
You may find the source code for this tutorial here.