The authentication-server is a node app that handles user registration, authentication & authorization with JWT.

Overview

Authentication Server

The authentication-server is a node app that handles user registration, authentication & authorization with JWT.

Here is the REPO.

Here is the DEMO.

How it works?

Registered users are stored in mongoDB and their password is hashed by bcrypt. When the user POSTs their credentials to the server, they recieve 2 Json Web Token (access & refresh).

On the client side user should set the authorization header(Bearer token) with access token. So user can be authorized by server with middleware. If the access token expired, renew the access token with refresh token by POSTing it to the "/token" endpoint.

Usage

  1. This server can be used as a standalone server. So the athentication system would be apart from the backend system. For authorization, JWT should be verified. JWT verification can be done in various programming languages. See: libraries.

  2. This server built with express.js. So it can be used on an existing express.js application.


Installation

git clone https://github.com/coluck/authentication-server.git
cd authentication-server
# replace .env.example with .env and customize it
npm i
npm start

API

No Method Endpoint Description
#1 POST /register Creates a new user in MongoDB and returns it with status 201
#2 POST /login Returns access & refresh tokens if user credentials is valid
#3 POST /token Returns a new access token if refresh token in body is verified
#4 GET /validate Returns user id if token in header is verified with middleware
No Request Body Response Body
#1 { username, email, password } { username, email, createdAt }
#2 { email, password } { access_token, refresh_token }
#3 { refresh_token } { access_token }
#4 Authorization: Bearer <access_token> User id that is logged in

Configuration

Configuration should made in the .env file, before run. .env.example file is below:

PORT=3000
MONGO_URL=mongodb://localhost:27017/<db_name>
ACCESS_TOKEN_EXPIRES_IN=5m
ACCESS_TOKEN_SECRET=c1ec3791140abfdddd...
REFRESH_TOKEN_EXIPRES_IN=1d
REFRESH_TOKEN_SECRET=2a4de696eb12838bc...

Scripts

  1. ACCESS_TOKEN_SECRET & REFRESH_TOKEN_SECRET (both should be different) can be securely created with:
npm run secret  # returns secret, paste it in .env
  1. MongoDB connection can be tested with:
npm run dbtest
  1. Start authentication-server:
npm start
  1. Start development server with nodemon:
npm run dev

Project Structure

.
├── src                       // Source Folder
│   ├── controllers           // Controllers in the API
│   │   ├── index.js
│   │   ├── login.js          // No: #1 /login
│   │   ├── register.js       // No: #2 /register
│   │   └── tokenRefresh.js   // No: #3 /token 
│   ├── public
│   │   └── index.html        // Mini User Interface built with vue
│   ├── authRouter.js         // All routings 
│   ├── middleware.js         // Authorize user with access token in header
│   ├── mongo.js              // Initialize MongoDB connection
│   ├── token.js              // Token Utils. Creates and verifies JWT
│   ├── userModel.js          // Mongoose Model and Schema
│   └── validation.js         // Joi validation for User Model
├── test
│   ├── mongoConnection.js    // "npm run dbtest" executes this
│   └── ...                   // login and regiter tests
├── .env.exmaple              // Rename it with ".env"
├── index.js                  // Entry file
└── server.js                 // authentication-server app

User Interface

Mini user interface is build with vue.js to show up what is going on. Available on root "/". It can be removed from server.js file. Screenshot_2021-05-02 authentication-sever User Interface Screenshot_2021-05-02 authentication-sever User Interface(1)

User Model

User Model is created with mongoose in userModel.js. userModel = { username, email, password }

Hash Password

Password is hashed with bcryptjs. For performance see also: bcrypt.

Validations

Implemented with joi in validation.js There are 2 validations(register and login) for request body.

Middleware

The isAuthenticated middleware verifies the jwt in authorization header. Simplified version of express-jwt. Used in /validate endpoint for testing purposes.

Logger

Logging made with morgan. The formats is "tiny". In server.js file it can be customized.

Todos

  • Refresh tokens can be saved in storage like redis or mongoDB
  • Login or Register limitation by ip address
  • Add JWT claims like iss, sub, aud...
  • Email verification
  • Login with username instead of email
You might also like...

Authentication solution for Express

Lockit Lockit is an authentication solution for Express. Check out the demo. It consists of multiple single purpose modules: lockit-login lockit-signu

Dec 28, 2022

A small project with 3 accounts mapped to 3 resources using auth0 as an authentication service.

Auth0WithExpressJS Quickstart install dependencies for backend and start backend cd Auth0WithExpressJS\Back && npm start install dependencies for fron

Aug 21, 2021

Role based authentication for NodeJS and ExpressJS

Authentication service made for ExpressJS and MongoDB using JWT. We tried to make it as clean and structured as possible. We also provide this documentation on how to install and integrate it with your own application.

Oct 3, 2021

An easy to use authentication system that can easily be built in to your Express + HBS web apps.

yoAuth An easy to use authentication system that can easily be built in to your Express + HBS web apps. Currently only supports local authentication,

Jan 21, 2022

Edge-side GitHub authentication

cloudflare-workers-github-auth Edge-side GitHub authentication example. Requirements node.js (v16.13.1 or later) Installation Clone this repository an

Feb 21, 2022

Authenticated server-side rendering with Nuxt 3 and Firebase 9

Authenticated server-side rendering with Nuxt 3 and Firebase 9.

Dec 23, 2022

node.js auth package (password, facebook, & more) for Connect and Express apps

everyauth Authentication and authorization (password, facebook, & more) for your node.js Connect and Express apps. There is a NodeTuts screencast of e

Dec 17, 2022

node.js/express module to authenticate users without password

Passwordless Passwordless is a modern node.js module for Express that allows authentication and authorization without passwords by simply sending one-

Dec 14, 2022

EveryAuth is the easiest way for your app to access APIs like Slack, Salesforce, or Github.

EveryAuth EveryAuth is the easiest way for your app to access APIs like Slack, Salesforce, or Github. import everyauth from "@fusebit/everyauth-expres

Dec 12, 2022
Comments
  • Additional Feature Ideas from reddit.

    Additional Feature Ideas from reddit.

    Here is the post. Screenshot_2021-05-03 r node - I made an authentication server that handles user registration, authentication authorization

    • Asymmetric signing for the JWTs. Only your auth server would have the key for token generation, but any app with the public key can verify the token.

    • Revoking JWTs. It looks like right now, if a bad actor were to get ahold of a token, you have no way to stop them. While the short lifespan of the tokens will get you most of the way toward preventing bad actors from doing anything too bad, the ability to revoke tokens is usually a pretty common security requirement.

    • Key rotation. There should be a mechanism in place that allows you to rotate the signing keys for your JWTs. It should allow you to add new signing key without invalidating all the JWTs currently in circulation.

    • Cookie support. Unfortunately for server rendered apps, storing the token in local storage isn't possible. Provided the token isn't too big, you could also shove it into a cookie so server rendered apps can also use the auth server.

    Thanks to cbadger85

    enhancement good first issue 
    opened by coluck 0
Owner
Oğuz Çolak
CS student
Oğuz Çolak
Tutorial Project : NodeJs API Multi Authorization Middleware with JWT

Tutorial How to Create API with multi route prefixs as well as Multi Authorization in NodeJs Installation npm install .env modify database informatio

Aung Kyaw Nyunt 10 Dec 10, 2022
Building an API on nodejs with registration system, authentication, CRUD of projects and tasks.

api-token-express Building an API on nodejs with registration system, authentication, CRUD of projects and tasks. API endpoints POST { "username":

MrDiniz 4 Jan 15, 2022
CASL is an isomorphic authorization JavaScript library which restricts what resources a given user is allowed to access

CASL (pronounced /ˈkæsəl/, like castle) is an isomorphic authorization JavaScript library which restricts what resources a given user is allowed to ac

Sergii Stotskyi 4.5k Dec 31, 2022
An authorization library that supports access control models like ACL, RBAC, ABAC in Node.js and Browser

Node-Casbin News: still worry about how to write the correct node-casbin policy? Casbin online editor is coming to help! node-casbin is a powerful and

Casbin 2.1k Dec 27, 2022
Boilerplate next.js app demonstrating how to implement authorization mechanisms using Permify

Permify Next.js Authorization Demo App This demo app shows how to implement authorization mechanisms to your Next.js application using Permify Node SD

Permify 7 Apr 22, 2022
This project shows how you can easily jwt protect your endpoints in web api apps built with node js.

JWT Protected NodeJs API This project shows how you can easily jwt protect your endpoints in web api apps built with node js. It is an easy and simple

Cihat Girgin 3 Oct 19, 2021
Oso is a batteries-included library for building authorization in your application.

Oso What is Oso? Oso is a batteries-included library for building authorization in your application. Oso gives you a mental model and an authorization

Oso 2.8k Jan 1, 2023
This package allows you to use Okta as your identity provider for use with Netlify's Role-based access control with JWT.

netlify-okta-auth This package allows you to use Okta as your identity provider for use with Netlify's Role-based access control with JWT. Who is this

Twilio Labs 8 Sep 17, 2022
Simple JWT Auth With TRPC prisma & next

Simple JWT Auth With TRPC prisma & next A sample JWT authentication using prisma, @trpc/server @trpc/client @trpc/react in Next.js Simple Usage copy .

Aris Riswanto 4 Aug 23, 2022
Simple, unobtrusive authentication for Node.js.

Passport Passport is Express-compatible authentication middleware for Node.js. Passport's sole purpose is to authenticate requests, which it does thro

Jared Hanson 21k Jan 7, 2023