Lecture: 2 mn

We live in a world where more than ever, everything and everyone is connected through the web or, has the potential to be. As a result a there is big amounts of data flowing all around us which why security is primordial to web applications and APIs. This article is going to look at implementing authentication in REST APIs using the well-known library PassportJS.

What is OAuth ?

OAuth is an open-standard authorization protocol or framework that describes how unrelated servers and services can safely allow authenticated access to their assets without actually sharing the initial, related, single logon credential. In authentication parlance, this is known as secure, third-party, user-agent, delegated authorization (csoonline.com).

What is Passport ?

I find the definition on their website is best:

Passport is authentication middleware for Node.js. Extremely flexible and modular, Passport can be unobtrusively dropped in to any Express-based web application. A comprehensive set of strategies support authentication using a username and password, Facebook, Twitter, and more.

Strategies in Passport are used to authenticate OAuth requests. This articles will give the implementation details for OAuth authentication with Google.

Google OAuth

Before configuring the Google Strategy on passport we need to create a new project on console.developers.google.com in order to obtain two keys: A client id and a client secret which are required by the passport strategy.

Create a new project

Once you have created your project, you will need to create the credentials, the id and secret mentioned earlier.

 

Create API Keys

Follow the subsequent steps and obtain your client id and secret. Now let’s have a look at some code implementing Google OAuth with passport.

The code above starts by import all the required dependencies, the two we are most interested in are passport and passport-google-plus-token. We are implementing passport on a REST API using JWT tokens, so we need to integrate passport with that. That is is where the google token strategy comes in by allowing us to authenticate users directly with Google and getting their profile information.

We only covered one strategy here. There are token strategies for all social media platforms. You can find them going through passport’s documentation.

Imprimer