This repo uses JSON Web Tokens and the jsonwebtoken package to implement token based authentication on a simple Node.js API.
This is a starting point to demonstrate the method of authentication by verifying a token using Express route middleware.
Several security features are included or planned to be added in accordance with the OWASP Password Storage Cheat Sheet so that this repository can be used as a secure and modern starting point for developing REST APIs
Any web application is insecure without a fairly secure server running it.
- Secure hashing method (argon2)
- Rate limit authentication endpoints
- Automatic HTTPS in production environment
- Email support for email verification and password reset mechanism
- Support for 2FA with email reset backup
node
and npm
check versions with node -v && npm -v
Redis needs to be installed on your local system for testing.
macOS users may need to install some prerequisite packages such as the XCode Command Line Tools
Windows users need to install some extra packages to build argon2:
npm install --global --production windows-build-tools
npm install -g node-gyp
- Clone the repo:
git clone https://github.com/MeepLabs/Node-Token-Authentication.git
- Install dependencies:
npm install
- Change
secret
inconfig.example.js
to something random - Change
database
inconfig.example.js
to your connection string - Rename
config.example.js
toconfig.js
- Start the server:
npm start
- Your API will be available at:
http://localhost:8080/api
Once everything is set up, we can begin to use our API by creating and verifying tokens.
The easiest way to test any REST API is with Postman but you can also use curl
This repository includes a Postman collection that you can import into Postman for testing.
Send a POST
request to http://localhost:8080/api/authenticate
with test user parameters as x-www-form-urlencoded
.
{
username: 'username-here',
password: 'password-here'
}
Curl example: curl -d '{"username":"username-here", "password":"password-here"}' -H "Content-Type: application/x-www-form-urlencoded" -X POST http://localhost:8080/api/create
Send a POST
request to http://localhost:8080/api/authenticate
with test user parameters as x-www-form-urlencoded
.
{
username: 'username-here',
password: 'password-here'
}
Curl example: curl -d '{"username":"username-here", "password":"password-here"}' -H "Content-Type: application/x-www-form-urlencoded" -X POST http://localhost:8080/api/authenticate
Send a GET
request to http://localhost:8080/api/users
with a header parameter of x-access-token
and the token.
You can also send the token as a URL parameter: http://localhost:8080/api/users?token=YOUR_TOKEN_HERE
Or you can send the token as a POST parameter of token
.