Authentication server using JSON Web Tokens for rest APIs
Explore the docs »
Report Bug
·
Request Feature
Table of Contents
The authentication server is written as a micro service following the mvc design pattern. You should easily be able to implement this into your own project. Before use, make sure to read this readme file and find out what you will be needing to get everything up and running.
The most important part is the .env file which must contain the following:
TOKEN_SERVER_PORT = 4000
REFRESH_TOKEN_SECRET = REFRESH_TOKEN_SECRET_GOES_HERE
ACCESS_TOKEN_SECRET = ACCESS_TOKEN_SECRET_GOES_HERE
DB_HOSTNAME = database.example.com
DB_USERNAME = exampledb
DB_PASSWORD = examplepassword
DB_DATABASE = exampledatabase
To generate the Refresh Token Secret and the Access Token Secret:
$ node
$ require("crypto").randomBytes(64).toString("hex")
Add a .env file in the src directory with the following information:
TOKEN_SERVER_PORT = 4000
REFRESH_TOKEN_SECRET = REFRESH_TOKEN_SECRET_GOES_HERE
ACCESS_TOKEN_SECRET = ACCESS_TOKEN_SECRET_GOES_HERE
DB_HOSTNAME = database.example.com
DB_USERNAME = exampledb
DB_PASSWORD = examplepassword
DB_DATABASE = exampledatabase
- NodeJS Dependencies:
"dependencies": {
"bcrypt": "^5.0.1",
"dotenv": "^11.0.0",
"express": "^4.17.2",
"jsonwebtoken": "^8.5.1",
"mysql": "^2.18.1",
"validator": "^13.7.0"
}
- Access to a MySQL Database
This is the SQL Table that needs to be added to the database
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`active` tinyint(4) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `username` (`username`);
--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
Add the ACCESS_TOKEN_SECRET to the application environment on you rest api or web application and use the tokenModel.js to validate the token for access.
-
The .env file must have the same ACCESS_TOKEN_SECRET as your authentication server.
-
To create a user: Send to http://yoursite.org/api/v1/user/create
{
"username":"your_username",
"password":"your_password",
"claim":"your_claim"
}
- To login (This will give you a refresh token, and a access token) Send to http://yoursite.org/api/v1/user/login
{
"username":"your_username",
"password":"password"
}
- To refresh a token send to http://yoursite.org/api/v1/user/refresh
{
"token":"your_refresh_token"
}
- To logout Send to http://yoursite.org/api/v1/user/logout
{
"token":"your_refresh_token"
}
Test Application using the validateToken script
/**
* Use the same environment configuration
*/
require("dotenv").config()
/**
* Include express, jwt and the tokenValidator
*/
const express = require("express");
const jwt = require("jsonwebtoken");
const app = express();
const port = process.env.TEST_APP_PORT || 8080;
function validateToken (req, res, next) {
if (!req.headers["authorization"]) {
res.status(400);
res.json({
"message":"requires authorization header to be set"
});
} else {
// Get Token from request header
const authorization = req.headers["authorization"];
const token = authorization.split(" ")[1];
if (token == null) {
res.status(400).send({
"message":"token not Present"
});
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (error, user) => {
if (error) {
res.status(403).send({
"message":"token invalid"
});
} else {
req.user = user;
next();
}
});
}
}
app.use (express.json())
app.listen(port, ()=> {
console.log(`Validation server running on ${port}`)
});
app.get("/secret", tokenValidator.validateToken, (req, res)=>{
console.log("Token is valid")
console.log(req.user.user)
res.send(`${req.user.user} successfully accessed the secret place`)
})
For more examples, please refer to the Documentation
- Basic POC up and running
- Based on Claims
- Should be able to work with rest API's as long as they have a token shared.
See the open issues for a full list of proposed features (and known issues).
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.
If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature
) - Commit your Changes (
git commit -m 'Add some AmazingFeature'
) - Push to the Branch (
git push origin feature/AmazingFeature
) - Open a Pull Request
Distributed under the MIT License. See LICENSE.txt
for more information.
Morten Haugstad - @codebarbarian
Project Link: https://github.com/codebarbarian/authentication-server
- Built upon Authenticate REST APIs in Node JS using JWT (Json Web Tokens) - By Prashant Ram