How to set up passport authentication
Nowadays most of the websites use authentication to validate the user and keep track of them. It is also very tiring to go through the registration process as well as to remember the passwords for different accounts. But with the rise of social networking, single sign-on using an OAuth provider such as Facebook o Twitter, Github or Google has become a popular authentication method. You need to have an account in one of the social platforms and you are good to go. In this article, we will discuss such an authentication process. We will be using Passport, which is a facilitator, an authentication middleware for node.js for such purpose.
In this article, we will talk about GitHub passport authentication
So Let's get started :
We will use express-generator to create our project and set the view to EJS.In the terminal go the desired directory where you want to create the project.
express --view=ejs github
It creates a project called github inside of your present directory and sets the view engine to an embedded Javascript Templating engine(EJS).
Now we need to go to the github folder and install the node modules
cd github
→ this opens the folder in VS Code
npm i
code .
We will have an index page that will have an anchor link for logging in through GitHub. Whenever the user logins for the first time we will create an entry in the database. We will be using the MongoDB database and mongoose which is an npm package that helps programmers to model their data.
npm i mongoose --save
this will install mongoose and save an entry in the package.json. In the app.js file of your project directory, we will have to require mongoose
var mongoose = require('mongoose');
We can also change the start script to “ nodemon ./bin/www
”, but before doing that we need to install nodemon package from npm. Nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when it detects file changes in the directory.
npm i nodemon
We will also make a folder called models in our project directory and make a new file called User.js for the Schema. Now inside Schema.js put the following code.
In the above code, we have depicted how the structure of the user model should be.
Okay, lets set up our view of the home page. I will keep this article oriented to understanding how to set up passport authentication and thus will have minimalistic view. In our views folder we have a index.ejs
file , this is our homepage. Just as we discussed earlier, we will add an anchor tag
<a href="/auth/github">Login with Github</a>
inside our body.
We also need to connect to our database, for that paste the code below in the app.js file after mounting express on app i.e
var app = express()
→mounting express on app
mongoose.connect("mongodb://localhost/github",{
useNewUrlParser: true,
useUnifiedTopology: true}
,(err)=>{
console.log("connected", err ? false: true)})
In the above code, we have connected to the “github” database and we are displaying a string and boolean → connected true
OR connected false
depending on the error. If there is an error it will display connected false
else connected true.
You need not worry if the database doesn’t exist because if it doesn’t then mongoose will create and connect with it.
Before handling the routes lets install the passport library and the Github strategy that will be needed to authenticate through Github OAuth provider
npm i passport --save
npm i passport-github --save
npm i dotenv --save
npm i express-session --save
npm i connect-mongo --save
After installing the libraries we will require them in our app.js file.
In the above code, we have required dotenv and express-session. Dotenv is a zero-dependency module that loads environment variables from a .env
file into process.env
and express-session makes sure that every user will be assigned a unique session which allows you to store the user state.
connect-mongo helps to store the session in the database
The next step will be to store the credentials that github provides when you create a project on developer console.
For that click here and fill out the form. After you are done with all the steps you would have the Client Id and Client Secret. Now in the project directory make a .env
file and store the client id and client secret in the .env
file. Now because of dotenv we can access the clientId and client_secret using process.env. For eg if inside .env file we had
clientId=someId
then process.env.clientId will be equal to someId .
We also need to set up the Strategy for Github to work.So if we go to the official documentation http://www.passportjs.org/docs/google/ we can find the code for it. We can make a folder called modules
and inside it make a passport.js
file.
In passport.js
paste the following code.
In the above code, we have required passport and the User model and have attached the strategy with passport. The second parameter of Github strategy is a verify function that takes access token, refresh token, profile and a callback(error, success) as arguments. The callback has either error or success.
After google strategy we have passport.serializeUser()
and passport.deserializeUser()
, the first one takes the success argument of the callback of the verify function and a callback and whatever is passed as a success argument in the callback is the first argument of the passport.deserializeUser()
. passport.serializeUser()
creates a session whereas passport.deserializeUser()
creates a key user
in the request.
Now for handling the auth routes, we make a different file auth .js inside the routes folder. After you have done that go to the auth.js
file and paste the code below
In the above code, we have handled the get request that is being sent when anyone clicks on <a href="/auth/login">Login with github</a
and pass it through passport.authenticate() and when a user enters the details of their Github account redirects to the URI given in the Authorized callback URL section in the Github developer console and also in the callbackURL key of the Github strategy.
Okay, we are close to the end now. For our app.js to work we need to require the strategy that we have defined in passport.js.We just need to require the passprt.js file in our app.js file. Put the code below dotenv.config()
in app.js
require('./modules/passport')
Now we will be able to look up the created user in the Github database using mongo. Give it a try!!!
If you find any difficulty or face any errors you can clone Github repository here.