This project consists of two Node.js microservices for generating and validating PASETO tokens.
This example demonstrates:
- User authentication using PASETO tokens
- Public and Private PASETO token usecases
- Token refresh functionality
- Token invalidation on logout
- A protected route that requires a valid token
-
paseto-auth
- Generates private or public PASETO tokens.
- Validates PASETO tokens.
-
paseto-microservice
- Contains secured endpoints.
- Validates and grants access for public PASETO tokens generated by
paseto-auth
.
-
Clone the repository
git clone https://github.com/Lilanga/paseto-token-generation-validation.git cd paseto-token-generation-validation
-
Install dependencies for both microservices
cd paseto-auth npm install cd ../paseto-microservice npm install
-
Environment Configuration:
- Create a
.env
file in bothpaseto-auth
andpaseto-microservice
directories. - Add necessary environment variables as required by each service. You can refer
.env.sample
file in the project root folder.
- Create a
Use following to generate secret key and private and public key pairs. Then update the .env
file with required information.
Feel free to use proper newline feed character \n
when coping public and private key contents as one line string.
Generate a secret key for Local tokens:
Copynode -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
Generate a key pair for Public tokens:
openssl genpkey -algorithm ED25519 -out private_key.pem
openssl pkey -in private_key.pem -pubout -out public_key.pem
- Run the microservices:
-
Start
paseto-auth
cd paseto-auth npm start
-
Start
paseto-microservice
cd paseto-microservice npm start
-
-
Generating Tokens:
- Use the
paseto-auth
microservice to generate PASETO tokens.
- Use the
-
Validating Tokens:
- Use the
paseto-auth
microservice to validate tokens including private tokens. - Access secured endpoints in
paseto-microservice
using valid public PASETO tokens.
- Use the
Use following curl commands to API endpoints to test.
- Login (Local Token)
curl -X POST http://localhost:3000/login \
-H "Content-Type: application/json" \
-d '{"username": "user1", "password": "password1", "tokenType": "local"}'
- Login (Public Token):
curl -X POST http://localhost:3000/login \
-H "Content-Type: application/json" \
-d '{"username": "user1", "password": "password1", "tokenType": "public"}'
- Access Protected Route (replace with the token received from login)
curl -X GET http://localhost:3000/protected \
-H "Authorization: Bearer <TOKEN>"
- Refresh Token (replace with the current token)
curl -X POST http://localhost:3000/refresh \
-H "Authorization: Bearer <TOKEN>"
- Logout (replace with the current token)
curl -X POST http://localhost:3000/logout \
-H "Authorization: Bearer <TOKEN>"
- Try to Access Protected Route After Logout (should fail)
curl -X GET http://localhost:3000/protected \
-H "Authorization: Bearer <TOKEN>"
This project is licensed under the MIT License. See the LICENSE file for details.