DEV Community

Cover image for Node.js Express Login example with PostgreSQL
Tien Nguyen
Tien Nguyen

Posted on • Edited on

Node.js Express Login example with PostgreSQL

In this tutorial, we're gonna build a Node.js Express Login & Registration example with PostgreSQL database that supports Token Based Authentication with JWT (JSONWebToken). You'll know:

  • Appropriate Flow for User Signup & User Login with JWT Authentication
  • Node.js Express Architecture with CORS, Authenticaton & Authorization middlewares & Sequelize
  • How to configure Express routes to work with JWT
  • How to define Data Models and association for Authentication and Authorization
  • Way to use Sequelize to interact with PostgreSQL Database

[For learning only]

Full Article: https://bezkoder.com/node-js-jwt-authentication-postgresql/

Token Based Authentication

Comparing with Session-based Authentication that need to store Session on Cookie, the big advantage of Token-based Authentication is that we store the JSON Web Token (JWT) on Client side: Local Storage for Browser, Keychain for IOS and SharedPreferences for Android… So we don’t need to build another backend project that supports Native Apps or an additional Authentication module for Native App users.

Alt Text

There are three important parts of a JWT: Header, Payload, Signature. Together they are combined to a standard structure: header.payload.signature.

The Client typically attaches JWT in Authorization header with Bearer prefix:

Authorization: Bearer [header].[payload].[signature]
Enter fullscreen mode Exit fullscreen mode

Or only in x-access-token header:

x-access-token: [header].[payload].[signature]
Enter fullscreen mode Exit fullscreen mode

For more details, you can visit:
In-depth Introduction to JWT-JSON Web Token

Overview of Node.js Express Login & Registration example

We will build a Node.js Express application in that:

  • User can signup new account, or login with username & password.
  • By User's role (admin, moderator, user), we authorize the User to access resources

This is our Node.js application demo running with MySQL database and test Rest Apis with Postman (logic is the same as using PostgreSQL).

These are APIs that we need to provide:

  • POST /api/auth/signup signup new account
  • POST /api/auth/signin login an account
  • GET /api/test/all retrieve public content
  • GET /api/test/user access User's content
  • GET /api/test/mod access Moderator's content
  • GET /api/test/admin access Admin's content

Flow for Signup & Login with JWT Authentication

The diagram shows flow of User Registration, User Login and Authorization process.

node-js-login-postgresql-example-flow

A legal JWT must be added to HTTP x-access-token Header if Client accesses protected resources.

You may need to implement Refresh Token like this:

node-js-express-refresh-token-example-flow

More details at: https://bezkoder.com/jwt-refresh-token-node-js/

Node.js Express Architecture with Authentication & Authorization

You can have an overview of our Node.js Express Login & Registration App with PostgreSQL in the diagram below:

Alt Text

Via Express routes, HTTP request that matches a route will be checked by CORS Middleware before coming to Security layer.

Security layer includes:

  • JWT Authentication Middleware: verify SignUp, verify token
  • Authorization Middleware: check User's roles with record in database

If these middlewares throw any error, a message will be sent as HTTP response.

Controllers interact with PostgreSQL Database via Sequelize and send HTTP response (token, user information, data based on roles…) to client.

For more details, implementation and Github, please visit:
https://bezkoder.com/node-js-jwt-authentication-postgresql/

Note: This tutorial is for learning purpose, better practice is to use HttpOnly cookies.

Further Reading

Fullstack (JWT Authentication & Authorization example):

You may need to implement Refresh Token like this:

node-js-express-refresh-token-example-flow

More details at: https://bezkoder.com/jwt-refresh-token-node-js/

Top comments (3)

Collapse
 
justintime4tea profile image
Justin Gross

We need to stop teaching people it's ok to roll their own identity. I've seen so many of these tutorials/articles lately. These kinds of posts should be hedged with a disclaimer like "not in production" or "for learning only" because this is exactly the kind of thing that will result in the building of wildly insecure applications and websites. Getting auth wrong hurts users. Teaching people to roll your own auth hurts developers and users. It's very closely related to people following stack overflow posts (by follow I mean copy pasta) where those posts are a "make it do a thing" answer and not a "do it right, how you would do it in production" answer.

withblue.ink/2020/04/08/stop-writi...

Collapse
 
sometimescasey profile image
Casey Juanxi Li

"we need to stop teaching people it's ok to roll their own xxx"

I think this sentiment is pretty anathema to the purpose of dev.to. The author of that article works for Azure. It's in Azure's interest to make all developers feel like auth is out of their wheelhouse and something they should be paying someone else to do. All the solutions he listed - Auth0, Azure, Google, Okta - are paid services which profit from the above mindset.

A company might very well come to the cost-benefit analysis that it makes more sense to pay Okta's fees than to write their own auth solution. Nobody disagrees with that. But that doesn't mean tutorials shouldn't exist, or that people shouldn't try to learn more about how auth works when they have the time, or when the stakes aren't all that high. I personally appreciate OP taking the time to create content on something that I want to understand better. Shaming them for their work seems unnecessary.

Collapse
 
cholasimmons profile image
Chola

wait...what??? rolling my own identity isn't good?