Skip to content

CodeBarbarian/authentication-server

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Contributors Forks Stargazers Issues MIT License LinkedIn


Authentication Server

Authentication server using JSON Web Tokens for rest APIs
Explore the docs »

Report Bug · Request Feature

Table of Contents
  1. About The Project
  2. Getting Started
  3. Usage
  4. Roadmap
  5. Contributing
  6. License
  7. Contact

About The Project

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")

(back to top)

Built With

(back to top)

Getting Started

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

Prerequisites

  • 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

Installation

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;

(back to top)

Usage

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.

{
  "username":"your_username",
  "password":"your_password",
  "claim":"your_claim"
}
{
  "username":"your_username",
  "password":"password"
}
{
  "token":"your_refresh_token"
}
{
  "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

(back to top)

Roadmap

  • 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).

(back to top)

Contributing

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!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

(back to top)

License

Distributed under the MIT License. See LICENSE.txt for more information.

(back to top)

Contact

Morten Haugstad - @codebarbarian

Project Link: https://github.com/codebarbarian/authentication-server

(back to top)

Acknowledgements

About

A authentication server written in NodeJS

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages