Social Authentication with Node.js Passport and JWT in SPA

OAuth 2.0 Flow with our website as example.com and Oauth Provider as Facebook

Client

Login page at example.com/login

Database schema

We want to support both emails and social auth providers for users to log in. To support both these use cases, I created my database schema to be something like:

Developer Apps

We will have to create an app for each of the Oauth providers. The process might be slightly different for each of them, but you will come across the fields below for all of them:

  1. App Name — The name of your app (for e.g. MyApp). This will be shown to the user while providing their credentials.
  2. App Logo — The logo for your app
  3. Client ID — This is ID of your application. We will need this to get the access token.
  4. Client Secret — This should never be mentioned anywhere in the client. Only server code should have this. Its also used to get the access_token.
  5. Redirect URI — The server route where the provider will callback with the authorization code.

Server

We will first start with adding the routes. For each provider, we usually have 3 routes:

  1. /api/auth/<provider> — This is called from our client (example.com)
  2. /api/<provider>/callback — This is called by the provider after authorizing the user. This is where we can then call the provider to get the access_token.
  3. /api/<provider>/delete — This can be called by the provider whenever it wants us to delete the userdata. This should be implemented to comply with the terms and conditions of the Oauth provider.
Node.js routes
loginFacebook code
passport_auth.js
BASE_SERVER_URL = <your server url>
JWT_SECRET = 'a random string'
# Facebook app credentials
FACEBOOK_APP_ID = 'XXXXXXXXXX'
FACEBOOK_APP_SECRET = 'XXXXXXXXXX'
# Google app credentials
GOOGLE_CLIENT_ID='XXXXXXX'
GOOGLE_CLIENT_SECRET='XXXXXXXXXXX'
Pass data to callback
var payload = { id: user.id, email: user.email, firstName: user.firstName, lastName: user.lastName }const token = jwt.sign(payload, process.env.JWT_SECRET);var cookiePayload = { user, token }res.cookie('auth', JSON.stringify(cookiePayload), { domain: process.env.DOMAIN_NAME });res.redirect(process.env.BASE_CLIENT_URL + '/loginsuccess'

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhishek Choudhary

Abhishek Choudhary

216 Followers

Enterprenuer | Ex-Facebook Hacker | Travel | Musician by aspirations