In JavaScript, you refresh the page using Show This code can be called automatically upon an event or simply when the user clicks on a link. Example JavaScript Refresh CodeClicking the above button will refresh the page/frame. Auto-RefreshYou can also use JavaScript to refresh the page automatically after a given time period. Here, we are refreshing the page 5 seconds after the page loads. This results in the page continuously refreshing every 5 seconds. You can achieve the same effect using the HTML meta tag. Other Refresh TricksBy including your refresh code in a function, you can have complete control over when the page is refreshed. Example 1Instead of having the "page refresh" function called automatically when the page loads, you can call it only when the user performs some action - such as clicking on a link. Example 2You can use conditional statements to determine whether or not to refresh the page. Here's a basic example of using a "confirm" box to ask the user if it's OK to refresh the page. By incorporating refresh code with a JavaScript function, you can trigger a refresh at any time that makes sense to your web application. HTML RefreshThe above examples will only work as long as the user has JavaScript enabled on their browser. You can also use HTML to refresh a page automatically once the page has loaded. This is achieved by using the HTML meta tag. Nodejs authentication using JWT a.k.a JSON web token is very useful when you are developing a cross-device authentication mechanism. Here is how token-based authentication works: The last step is frustrating, we can’t ask users to log in each and every single time once the token is expired. There are two ways to solve this:
I have covered token-based authentication in this article in detail. In this Nodejs authentication tutorial, I am going to build a simple/boilerplate solution to handle the refresh token mechanism in Nodejs authentication.
So let’s begin. Creating the ProjectLet’s get straight to the code. You need to create a new folder and run the following command to initialize the new Nodejs project. This will create a new package.json file. Installing dependencis You need few dependencies to run the project. Install them using the following command. npm i --S express body-parser jsonwebtoken Once they are installed, you are good to go. Adding GitignoreYou need to add this file to avoid certain folders being added to the Git repository. To do this, you need to create a new file and name it .gitignore and add the following line. This means, avoid adding node modules folder in the git repository. Ok, let’s write some code. Creating Server and adding routesI am going to use express to create a Nodejs server. Here is the code. app.js const express =
require('express') router.get('/', (req,res) => {
router.post('/login', (req,res) => { router.post('/token',
(req,res) => { router.use(require('./tokenChecker')) router.get('/secure', (req,res) => { app.use(bodyParser.json()) Here is the config file. config.json { In the login route, we are doing the token generation. Notice these two lines: const token = jwt.sign(user, config.secret, {
expiresIn: config.tokenLife}) I am using different secrets and times to expire for both of the keys and storing the keys in an array using the following code. tokenList[refreshToken] = response
In the token route, I am expecting the refresh token in the payload, if the payload exists, I am checking if it is a valid token. If it is a valid token, I am creating a new token and sending it back to the user. This way user doesn’t need to log in again. Creating middleware to authenticate the API callsYou need to have a piece of code that always executes and check if the token coming in the API calls is valid or not. If you have noticed, I have added this middleware code in the Server code. router.use(require('./tokenChecker')) Here is the code for this middleware. tokenChecker.js const jwt =
require('jsonwebtoken') module.exports = (req,res,next) => { It’s simple token validation. This way all the API calls which are below this middleware have to provide a valid token to consume the system’s resources. Testing the codeLet’s do some testing. Run the code using the following command. Open your favorite API testing tool, mine is Postman, and hit the /login API route. URL: http://localhost:3000/api/login Here is the sample screenshot to refer to. Now copy the token and use it to access the /secure API route. Refer to this screenshot for help. Now, let’s do a token exchange, shall we? You need to call /token route and provide the refresh token to obtain a new token. Refer to the screenshot below for the payload example. Download the codeThe source code is open source and you can clone, distribute and download it from the Github. Click here to view the repository. ConclusionNodejs authentication using tokens is an integral part of web development. You need to use the refresh token mechanism for the seamless flow of the application. We covered the basics of it and I am sure you can take it from there. |