JoinDownload
This is drafted post. Please setdraft: falsein this .mdx file once ready to be published.

GitHub Authentication with Passport.js

2 Min Read

Henry Boisdequin

In this article, I will cover how to do GitHub authentication with Passport.js. Writing your own authentication can be a nightmare. Using a trusted company such as GitHub is more secure, makes it easier for the user to sign in, and gives you a lot of pre-auth-filled (yes, I know that is not a word) information about the user (e.g. bio, profile image, email, etc). For this tutorial, you will need Node. I will be using Node version 15.8.0 but feel free to use any Node version higher than 13. With that out of the way, let's get right into it.

What is Passport.js?

Passport.js is an authentication library that is simple and unobtrusive. It's by far the most popular authentication library to use when dealing with GitHub authentication. It also has a "sub-library" called passport-github. Passport-GitHub makes it extremely easy to create a new GitHubStrategy and authenticate the user.

Passport: https://github.com/jaredhanson/passport Passport-GitHub: https://github.com/jaredhanson/passport-github

Creating a new GitHub OAuth App

In order to start authenticating with GitHub, we need to create a new GitHub OAuth App. Follow this guide to create a new GitHub OAuth App (set the callback URL to http://localhost:4000/auth/callback and the homepage URL to http://localhost:4000). Creating a GitHub OAuth App is mandatory if you want to authenticate with GitHub. By creating one, you will receive a GitHub client ID and GitHub client secret. If ever you show your application to anyone (this includes pushing it to GitHub), make sure that your .env file is inside your .gitignore. This will stop anyone from looking at your GitHub client ID and secret. Now that we have our GitHub client ID and secret, let's start coding!

Coding the GitHub Authentication

Create a new folder called github-auth:

mkdir github-auth
cd github-auth/

Let's initialize a new Node project by running npm init -y. Now open the folder in your favorite code editor (mine is VSCode).

code .

Let's install our dependencies:

npm install passport-github passport express --save

After we've done that, create a new file called index.js.

touch index.js

Firstly, let's create a "Hello World" express app:

index.js

const express = require("express")
const app = express()
const PORT = 4000
app.get("/", (req, res) => {
res.send("Hello World!")
})
app.listen(PORT, () => {
console.log(`Server is up and running on localhost:${PORT}`)
})

To start our server, run node index.js. If you go to localhost:4000, you should see "Hello World!"! It works, great! Now, let's learn how to authenticate with GitHub.

index.js

const express = require("express")
const passport = require("passport")
const GitHubStrategy = require("passport-github").Strategy
let user = null
const PORT = 4000
const GITHUB_CLIENT_ID = "YOUR CLIENT ID"
const GITHUB_CLIENT_SECRET = "YOUR CLIENT SECRET"
const callbackURL = "http://localhost:4000/auth/callback"
const app = express()
passport.use(
new GitHubStrategy(
{
clientID: GITHUB_CLIENT_ID,
clientSecret: GITHUB_CLIENT_SECRET,
callbackURL: callbackURL,
},
(accessToken, refreshToken, profile, cb) => {
user = profile
return cb(null, profile)
}
)
)
passport.serializeUser((user, cb) => {
cb(null, user)
})
app.use(passport.initialize())
app.get("/", (_, res) => {
res.send("Go to /auth to authenticate!")
})
app.get("/auth", passport.authenticate("github"))
app.get(
"/auth/callback",
passport.authenticate("github"),
(req, res) => {
res.redirect("/me")
}
)
app.get("/me", (_, res) => {
res.send(user)
})
app.listen(PORT, () => {
console.log(`Server is up and running on localhost:${PORT}`)
})

If you run node index.js and go to /auth, you should see yourself getting redirected to GitHub and then seeing your JSON GitHub profile on our website! It works! Now, let's understand this code.

Code explanation

In the first 3 lines of the code, we are importing the necessary modules we need to use. Express is for our server and passport-github and passport are both for the authentication. Next, we define some variables. The user variable is where we are going to store all of the user's information. The PORT variable shows the port that our server is running on. For the next three variables, make sure they match what you received from creating a GitHub OAuth app. Next, we initialize a new GitHub strategy. The function at the end of that part will be called every time the user finishes authenticating with GitHub. In that function, we set the current user to the user we received from GitHub and return a callback function with the user. After that, we initialize our authentication or passport. After that, we set up our server's routes:

"/" = Simple message to tell the user to authenticate with GitHub

"/auth" = Authenticates the user with GitHub, leads them to the GitHub login page

"/auth/callback" = Gets called after "/auth" and redirects the user to "/me"

"/me" = shows the current user's information

After that, we run our server and now it's working!


I hope you learnt how to authenticate users with GitHub in this article. I would recommend taking this further by implementing GitHub authentication in any web app you would like to build next. Some ideas include a Workout Tracker, Blog platform, e-commerce site, the list goes on and on. Thanks for reading!

Henry

CONTENT
What is Passport.js?Creating a new GitHub OAuth AppCoding the GitHub AuthenticationCode explanation

Links

DownloadDocChange LogsCookiesTerms & ConditionsPrivacy PolicyContact Us

Apps & Integrations

HTTPGraphQLWebsocketSocketIO

Firecamp Newsletter