RiskTM / jwt-token-example

This is a barebones JWT Token authentication implementation.
0 stars 0 forks source link

JWT-token-example

Description

This is a example implementation for jsonwebtoken (JWT) authentication. Because the focus was on the backend the frontend is really simplistic. This project was build with NodeJS. For the server expressjs was used and postgresql for the database.

This project could be extendend but my focus was on getting to know JWTs.

Table of Contents

How to Install and run

Before you can install be sure to have nodeJS installed.

cd /path/to/JWT-token-example/
npm install

now change the .env file to fit your specification. For help see the next section.

The expiration time can be changed in /services/createTokens.js. By default 15m for the accessToken and 7d for the refreshToken are selected.

The DB need to have the table "PG_DB_USER" with two columns username and password. For a refrence look at init.sql

node server.js # for development use: npm run devStart

.env explained

# postgres settings
PG_HOST="0.0.0.0" 
PG_PORT="5432"
PG_USER="admin"
PG_PASSWORD="admin"
PG_DATABASE="jwt_local_test"
PG_DB_USER="jwt_whitelist" # this is the table for the users

PORT="3000" # the port the server listens to
ROOTPATH="/path/to/repo"

# key for the JWT generation
ACCESS_TOKEN="access_token_key"
REFRESH_TOKEN="refresh_token_key"

How to use the project

The server has 4 main tasks:

Routes:

output = { accessToken: "token...", refreshToken: "token..." }

- the route `"/token"` takes the body `{refreshToken: "token"}` and returns a new accessToken as an object.
- the routes `"/api/.."` need an accessToken given to the post request as a BEARER token additionally the body can contain a refreshToken which will be checked if the accessToken is expired. This will be passed to `middleware.js` which will check if the tokens are valid and if you get access to the api.
```js
headers = {
        'content-type': 'application/json',
        authorization: 'Bearer toke'
}

optional: body = {
        refreshToken = "token"
}

Technologies used

JavaScript NodeJS ExpressJS jwt postgresql HTML