Thursday, December 28, 2017

Getting started with Passport in Node.js

Hi Readers,

This post is on getting started with Passport. Here I'll explain on how to create an API that will support to add users to a datasource and login and logout the user and do authenticated calls.

Here we do bit of dependency injection to make it easier to add any type of dataaccess class so that you can use your own data access class and use your own data source.

When it comes to authentication for Node and Express Passport is a famous NPM package which supports multiple strategies. Here I'll be explaining the local strategy which will use a local data source. there are other options like using facebook or google as the strategy to authenticate the user.

The sample code is shared in the below GIT repository
https://github.com/guruparan/BlogSample/tree/master/NodeAuthAPI

The script files and the usages are explained below

app.js
The main node application which is the startup file for the API, this application runs in port 5000.

authroute.js

The API for authentication which has the below POST methods
http://localhost:5000/auth/signup
creates a user, the user should be provided in the below format
{
"username":"guru",
"password":"123"
}

http://localhost:5000/auth/login
Authenticates a user, the request is same as above.

http://localhost:5000/auth/logout
A direct post to the server, will logout the user

loginstrategy.js
The strategy for validating the user, will query the database and check whether its  a valid login.

passportauth.js
Setup Passport to store and retrieve the user from the session.

userdataaccess.js
Used to access the datastore to create and verify users. Here mongoose and mongo db is used to store users.

The code is commented to make it more understandable.
Just download and run the below commands to try out the sample API.

npm install
npm start

Happy Coding.
Guru