Skip to content

Repository files navigation

Node.js Authentication & Role-based Authorization API

A simple example using Express, PostgreSQL, and JWTs in HttpOnly cookies.

Getting Started

Prerequisites

Once all prerequisites are installed, run the following in your terminal:

git clone git@github.com:opes/node-auth.git
cd node-auth
npm i
npm run setup-db
npm run start:watch

Usage

Create users by POSTing to the /api/v1/users endpoint with an email, password, and role (currently supports Admin or User):

# Create an Admin user
curl -d '{"email":"admin@example.com","password":"hunter2","role":"Admin"}' -H 'Content-Type: application/json' http://localhost:3000/api/v1/users
# Create a standard user
curl -d '{"email":"user@example.com","password":"hunter2","role":"User"}' -H 'Content-Type: application/json' http://localhost:3000/api/v1/users

Log in by POSTing the email and password to the /api/v1/session endpoint:

curl -d '{"email":"user@example.com","password":"hunter2"}' -H 'Content-Type: application/json' http://localhost:3000/api/v1/session

Once logged in, you'll be able to access the following routes:

GET /api/v1/users
GET /api/v1/users/:id
PATCH /api/v1/users/:id (only available to the Admin role)

Any additional routes can use the authenticate middleware to require authentication:

// in some controllerimport{Router}from'express';importauthenticatefrom'../middleware/authenticate.js';exportdefaultRouter()// add the `authenticate` middleware to the route handler.get('/',authenticate,async(req,res,next)=>{res.send("if you see this, you're logged in");});

To make a route only available to certain roles, use the authorize middleware:

// in some controllerimport{Router}from'express';importauthenticatefrom'../middleware/authenticate.js';importauthorizefrom'../middleware/authorize.js';// you can add the `authenticate` and `authorize` middlewares to an arrayconstensureAdmin=[authenticate,authorize(['Admin'])]exportdefaultRouter()// ...then add the middleware array to the route handler.get('/',ensureAdmin,async(req,res,next)=>{res.send("if you see this, you're logged in as an Admin");});

Testing

npm run test:watch

About

A super simple example of a user authentication & authorization API in Node.js using Express, PostgreSQL, and JWTs.

Topics

Resources

Stars

3 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages