This example is to demonstrate JWT authentication and refresh token authentcaiton and should not be used in production as is.
Mono repo workspace using Nrwl Nx workspace.
Made using Nestjs.
Made using Angular 10
MonogoDB hosted on mongodb.com
Clone the project
git clone https://github.com/niallconaghan/nx-auth-nestjs-angular.git
Install packages, from the root directory, run:
npm install
To run the client, from the root directory, run:
nx serve client
To run the API, run:
nx serve api
The api will serve on port 4500
by default.
The api gettings environment variables from a .env
file.
This file needs to be created in:
apps/api/
To change what port the api is served on:
PORT=<port number>
Add your monodb.com url:
MONGO_DB_URL=<mongodb url>
Add your JWT secret:
JWT_SECRET=<your secret>
Add your password salt:
HASH_SALT=<salt number>
Example .env
PORT=1337
MONGO_DB_URL=mongodb+srv://<username>:<password>@database.5555.mongodb.net/users?retryWrites=true&w=majority
JWT_SECRET=s0m3s3cret
HASH_SALT=10
The client will run on port 4200
by default.
Register a user with a username and password
Login as an authenticated user
Request protected data
After one minute your JWT token will expire
Upon requesting protected data the client will make a request to get a new JWT token using the refresh_token
received after logging in.
After 2 minutes of no action the refresh_token
will expire.
Any attempts to fetch protected data will log the user out.
Route guards are in place to block access to the content page if you are not authenticated and block access to the login page if you are authenticated
Register a user
Login with that registered user
Request protected data
Expired JWT, request new token via refresh_token
Authenticated again after refresh
Expired refresh token, logging out