Friday, February 4, 2022

Node.JS Custom Stateless Authentication

Simple API Authentication

If you are looking for a low cost authentication solution for your Node.JS Express API then you have come to the right place. In this post I will show you how setup a very simple authentication system using JWT



View the git project here.

Create project

npm init
npm install express
npm install express-jwt

Create a file named index.js in the root and add the following code:

const express = require('express')
const app = express()
const port = 3000
app.get('/', (req,res=> {
    res.send('Hello World')
})
app.listen(port, ()=> { console.log(`app listening on http://localhost:${port}`); })
Now open the package.json file and look for the section called "Scripts"

Add the code colored in white:
{
  "name""auth-jwt-example",
  "version""1.0.0",
  "description""",
  "main""index.js",
  "scripts": {
    "test""echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },
  "repository": {
    "type""git",
    "url""https://jasonanthony@dev.azure.com/jasonanthony/auth-jwt-example/_git/auth-jwt-example"
  },
  "author""",
  "license""ISC",
  "dependencies": {
    "express""^4.17.1",
    "express-jwt""^5.3.3"
  }
}
Now open a command prompt and navigate to where you project is stored. Type and run the command "npm start"

C:\Users\[the path to your project]> npm start

The result should look like the following:

> auth-jwt-example@1.0.0 start C:\Users\[user]\Web Projects\Custom-JWT-Auth\auth-jwt-example
> node index.js

app listening on http://localhost:3000

You should see "Hello World" if you open a browser and go to the address "http://localhost:3000"

Adding that start script is optional as that is just the way I prefer to start my applications. If you are unfamiliar with how the Scripts section works in the package.json file of a node.js project I would recommend reading up on it.

Personally I do not recommend putting all of your routes in your index.js file as that will get messy really fast if you're building a production application. I prefer to create a folder called "routes" and add an express router file called "index.js" or "router.js" inside of it. There you can add all of your routes and have those routes call a module so your router file is nice and clean and easy to read.

So now I'm going to move my Hello World route to the router. 

Edit the index.js at the root of the project as shown below. You can just delete the contents and copy and paste the following:

const express = require('express')
const app = express()
const port = 3000
var routes = require('./routes')
app.use(routes);

app.listen(port, ()=> { console.log(`app listening on http://localhost:${port}`); })

Notice that we removed the code that handled the get request to display Hello World and added a variable called routes and told our app to "use" it. Now if you have not done so already create a folder called "routes" at the root of the project and create a new file named "index.js" inside of it. Since we named the file "index.js" node is smart enough to realize that it is the default file to run code when we call just the directory. require('./routes') could also be written as require('./routes/index.js') but we don't need to because node will know what to do and it saves us some typing.

Add the following code to the file at "./routes/index.js"
const express = require('express'),
    router = express.Router();

router.get('/', (req,res=> {
    res.send('Hello World')
})

module.exports = router;


This is now our router file that will contain all of our routes going forward. At this point it is a good idea to run the application and make sure it is working just the was it was before all of these changes. Open the command prompt back up and run the command "npm start." Use your browser to navigate to "http://localhost:3000" and you should be greeted with "Hello World" just as before.



No comments:

Post a Comment