Website Posts

[Best-Practices] Securing NodeJS Express APIs with JWT Authentication and custom Authorization

Overview


A Node.js library for use as Express middleware to secure endpoints with JWTs. The implementation uses a JWT endpoint of an Authorization Server to get the keys required for verification of the token signature. There is also an example Express app that shows how to use the library.

Package: https://www.npmjs.com/package/jsonwebtoken

Using the JSON web token, we can simply authenticate each and every request on our server. As a standard / best practice, we can use JWT (JSON web token) middleware to validate all requests.

JWT Middleware


  const jwt = require('jsonwebtoken')

  module.exports = (expectedRole) => (req, res, next) => {

  const authHeader = req.get('Authorization')
  if (!authHeader) {
    const error = new Error('Not authenticated.')
    error.statusCode = 401
    throw error
  }

  const token = authHeader.split(' ')[1]
  if (!token) {
    const error = new Error('Not authenticated.')
    error.statusCode = 401
    throw error
  }

  let decodedToken
  try {
    decodedToken = jwt.verify(token, process.env.SECRET_KEY)
  } catch (error) {
    error.statusCode = 401
    throw error
  }

  if (!decodedToken) {
    const error = new Error('Not authenticated.')
    error.statusCode = 401
    throw error
  }

  const role = decodedToken.role

  const authorised = expectedRole.includes(role)
  if (!authorised) {
    const error = new Error('Not authorised.')
    error.statusCode = 401
    throw error
  }

  req.user = decodedToken
  next()
}

This middleware has been prepared and exported. Therefore, we need to include it in our routes file and pass it to the expected role, so in our JWT middleware, we will validate the request with the JWT token, then verify that the user has access to an expected role (this role saved in the database) to this endpoint.

Routes File


 const express = require('express')
 const router = express.Router()

 const auth = require('./auth/index')
 const admin = require('./admin/index')
 const common = require('./common/index')
 const authorize = require('../middleware/jwtAuth')

 router.use('/auth', auth)
 router.use('/admin', authorize(['admin']), admin)
 router.use('/common', authorize(['admin', 'user']), common)

 module.exports = router 

Now that we have set up our authentication and authorization middleware in our routes, we are passing the required role to access these routes. These roles will be checked against our user role.

Our middleware simply next() the request if the user has a valid JWT token and is authorized to access this route, otherwise, it will throw the global error that is caught by the express global error handler.

November 08, 20222 minutesSmit GajeraSmit Gajera
How to Connect Gatsby to WordPress

Gatsby is a blazing-fast website framework for React. It allows developers to build React-based websites within minutes.

WordPress

WordPress is a free and open-source content management system written in PHP and paired with a MySQL or MariaDB database. Features include a plugin architecture and a template system, referred to within WordPress as Themes.

Integrate Gatsby with WordPress

Install gatsby-source-wordpress package

npm install gatsby-source-wordpress

gatsby-config.js file

add the gatsby config file in the following code

 plugins: [
    ...
    {
        resolve: `gatsby-source-wordpress`,
        options: {
            // Specify the URL of the WordPress source
            baseUrl: `localhost:8888/wordpress`,
            protocol: `http`,
            // Indicates if a site is hosted on WordPress.com
            hostingWPCOM: false,
            // Specify which URL structures to fetch
            includedRoutes: [
              '**/posts',
              '**/tags',
              '**/categories'
            ]
        }
    }

Now connect your gatsby website and Wordpress.

Here is an example of the GraphQL API query

import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout"
import SEO from "../components/seo"

export default ({ data }) => {
  return (
      {data.allWordpressPost.edges.map(({ node }) => (
        <div>
          <p>{node.title}</p>
        </div>
      ))}
  )
}
export const pageQuery = graphql`
  query {
    allWordpressPost(sort: { fields: [date] }) {
      edges {
        node {
          title
          excerpt
        }
      }
    }
  }

Hope this helps.

February 28, 20221 minuteVatsal SakariyaVatsal Sakariya
Top 5 web design trends that will shape the future

Here are a few modes for web design trends

Dark Mode

They look very modern and also very pleasing to the eye. They look amazing and stand out from other colors. Sometimes the most stunning web designs begin. Dark themes are great for OLED screens, which extend the life of the screen and also save power. The best part is that it is very easy to see and not too bright. If you are thinking of keeping something simple you can simply choose a dark mode and it can easily have a good effect on your mood.

3D Elemental

3D visuals are very interesting and they always make people wait for them. This is more about technology and the price tag and so the designers are working together to develop a 3D elemental design without any use of NASA tire equipment. Until VR becomes a trend, one can easily use these 3D designers and experience the reality of matter. Interactive 3D design lasts longer and looks more attractive at the same time. So you can also use this to break down the boundaries between space and reality. It looks great and you will enjoy the mode to the fullest.

Floating Elements And Layers

If you like something with more depth then this is for you as these soft shadows with floating elements add more life to the web page. It has a 3D light look and is not just graphics. One can use photos, text and move it forward. These effects and the feel of the web page will be lighter and the floating elements will make it more beautiful. If you are a travel company you may choose to have this one for your site.

Graphics and Photography

If you want to make it a little more memorable, you need this. You can put graphics on top of your favorite photographs. You can also be creatively wild and get your creativity for it. This can be versatile as it is like a collage of items with which it can add special versions and features to make it look more attractive. The person needs to match the pictures and graphics according to the brand personality. How people can interpret a photograph can take away the style. It's a sophisticated theme.

White Space With Solid Frames

Here you can easily play with solid compositions and also use different ways of using white space and with that you can give a better texture to their style and also use cleaner framing. Lots can be done here with fitting shapes in white spaces. This can brighten up all the visuals and make it very easy to order and separate different parts of the page. Designers love this type of framing and this is a simple website design if you want simplicity.

December 31, 20213 minutesKishan SavaliyaKishan Savaliya
How to connect strapi CMS in gatsby website

Gatsby

Gatsby is a blazing-fast website framework for React. It allows developers to build React-based websites within minutes.

Strapi CMS

Strapi is an open-source, Node.js based, Headless CMS that saves developers a lot of development time while giving them the freedom to use their favorite tools and frameworks.

Integrate Gatsby with Strapi

Install gatsby-source-strapi package

npm i gatsby-source-strapi

gatsby-config.js file

  • add the gatsby config file in the following code

plugins: [
    {
        resolve: `gatsby-source-strapi`,
        options: {
            apiURL: "your strapi server",
            contentTypes: ["restaurant"], //add your collections name
            queryLimit: 1000,
        }
    }
]

Now connect your gatsby website and strapi CMS

  • Here is an example of the GraphQL API query
import { StaticQuery, graphql } from 'gatsby';

const query = graphql`
  query {
    allStrapiRestaurant {
      edges {
        node {
          strapiId
          name
          description
        }
      }
    }
  }
`

const IndexPage = () => (
  <StaticQuery
    query={query}
    render={data => (
      <ul>
        {data.allStrapiRestaurant.edges.map(restaurant => (
          <li key={restaurant.node.strapiId}>{restaurant.node.name}</li>
        ))}
      </ul>
    )}
  />
);

export default IndexPage;

Hope this helps.

September 01, 20212 minutesVatsal SakariyaVatsal Sakariya
How to make a Progressive Web App

What is a PWA?

A Progressive Web App (PWA) is a hybrid of a regular web page and a mobile application. A PWA combines features offered by most modern browsers with the benefits of the mobile experience. They are built using standard web technologies, including HTML, CSS, and JavaScript. The functionalities include working offline, push notifications, and device hardware access and enabling creating user experiences similar to native applications.

How to make a PWA

Following Below steps

  • Create an app manifest.json file
  • Add it to your base HTML template
  • Create the service worker
  • Serve the service worker on the root of the scope you used in the manifest
  • Add a block to your base HTML template file
  • Site deploy in your server

Create an App Manifest

  • Add the following information in 'manifest.json'
 {
    name: `Name`,
    short_name: `Sort name`,
    start_url: `/`,
    display: `standalone`,
    icon:  `Favicon icon`,
    icons: [
       {
        "src": "icon by size",
        "sizes": "144x144",
        "type": "image/png",
        "purpose": "any"
      },
      {
        "src": "icon by size",
        "sizes": "192x192",
        "type": "image/png",
        "purpose": "maskable"
      },
      {
        "src": "icon by size",
        "sizes": "512x512",
        "type": "image/png",
        "purpose": "maskable"
      }
    ],
  theme_color: `Theme color`,
  background_color: `Background color`,
  ]
 }
  • Manifest.json file in add this type of code including name, short_name, start_url, display, icon, icons, theme_color, background_color.

Add the Manifest to Your Base HTML Template

  • Add the following line in yore 'index' file

Create offline.html as an Alias to index.html

By default, the service worker code below will render /offline.html instead of any resource it can't fetch while offline. Create a file at /offline.html to give your user a more helpful error message, explaining that this data isn't cached and the user is offline.

Create a Service Worker

  • Create one file in yore root (sw.js)
  • Link the sw.js file in the body tag

We have created some pages like

  1. Home page (/)
  2. Blog page (/blog)
  3. Contact information (/contact)
  4. Resume (/resume)
  5. offline.html
  • Add the code in your sw.js file
self.addEventListener("install", function(event) {
   event.waitUntil(preLoad());
});

 var preLoad = function(){
  return caches.open("offline").then(function(cache) {
    return cache.addAll(["/blog/", "/blog", "/", "/contact", 
 "/resume", "/offline.html"]);
    });
 };

 self.addEventListener("fetch", function(event) { event.respondWith(checkResponse(event.request).catch(function() 
  {
     return returnFromCache(event.request);
   }));
   event.waitUntil(addToCache(event.request));
  });

  var checkResponse = function(request){
   return new Promise(function(fulfill, reject) {
     fetch(request).then(function(response){
       if(response.status !== 404) {
         fulfill(response);
       } else {
         reject();
       }
     }, reject);
   });
  };

  var addToCache = function(request){
   return caches.open("offline").then(function (cache) {
     return fetch(request).then(function (response) {
       console.log(response.url + " was cached");
       return cache.put(request, response);
     });
   });
  };

  var returnFromCache = function(request){
   return caches.open("offline").then(function (cache) {
     return cache.match(request).then(function (matching) {
      if(!matching || matching.status == 404) {
        return cache.match("offline.html");
      } else {
        return matching;
      }
     });
   });
  };
  • Servicer worker file add your body tag

load the service worker file in

<script>
   if (!navigator.serviceWorker.controller) {
   navigator.serviceWorker.register("/sw.js").then(function(reg) {
         console.log("Service worker has been registered for scope: " + reg.scope);
     });
 }
 </script>

Last step

  • Deploy code in yore live site
  • Create lighthouse report and check PWA
July 28, 20214 minutesVatsal SakariyaVatsal Sakariya