avatarCaleb

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

5592

Abstract

n>(<span class="hljs-string">'/protected'</span>, verifyToken, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> { res.<span class="hljs-title function_">json</span>({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Protected route accessed!'</span>, <span class="hljs-attr">user</span>: req.<span class="hljs-property">user</span> }); });</pre></div><h1 id="0e80">Part 4: Testing JWT-Protected Endpoints</h1><p id="4350">After implementing JWT authentication, it’s vital to ensure that our endpoints are working as expected.</p><p id="943d">Testing can be done through a web browser for open routes or using tools like Postman for the secured endpoints.</p><p id="4697">Here’s how you can test the authentication flow:</p><h2 id="3117">Step 1: Testing the Unprotected Route in a Browser</h2><p id="2413">You can simply open your web browser and navigate to <code>http://localhost:3000/</code>. You should see the welcome message: "Welcome to the JWT Tutorial."</p><h2 id="8da7">Step 2: Testing the Login and Protected Endpoints Using Postman</h2><p id="42ee">Postman is a popular tool for testing APIs. Follow these steps to test the login and protected routes:</p><ol><li>Testing the Login Endpoint</li></ol><ul><li>Open Postman.</li><li>Set the request method to <code>POST</code>.</li><li>Enter the URL <a href="http://localhost:3000/login."><code>http://localhost:3000/lo</code>gin.</a></li><li>Click “Send” to make the request.</li><li>You should receive a JSON response containing the token.</li></ul><figure id="4c63"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*W4yYDoM3h7vKXpdr3GDsfg.png"><figcaption></figcaption></figure><p id="6cf0">2. Testing the Protected Endpoint with the Token</p><ul><li>Copy the token from the login response.</li><li>Create a new request in Postman.</li><li>Set the request method to <code>GET</code>.</li><li>Enter the URL <a href="http://localhost:3000/protected."><code>http://localhost:3000/protec</code>ted.</a></li><li>Under the “Headers” tab, or directly under the “Authorization” tab, add a key <code>Authorization</code> with the value <code>Bearer YOUR_TOKEN</code> (replace <code>YOUR_TOKEN</code> with the copied token).</li><li>Click “Send” to make the request.</li><li>You should receive a JSON response with the message “Protected route accessed!” and the user details.</li></ul><figure id="5e81"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*8SW5pep3d1olsYi3dX0ZlQ.png"><figcaption></figcaption></figure><p id="a7ca">3. Testing the Protected Endpoint without the Token or with an Invalid Token</p><ul><li>Repeat the steps for the protected endpoint but omit the token or use an invalid one.</li><li>You should receive a 403 status code, indicating that access is forbidden.</li></ul><figure id="8896"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*n-cQA-tHlx041mZ3Xcviuw.png"><figcaption></figcaption></figure><p id="ff26">By following these steps, you’ve ensured that the JWT authentication is correctly implemented in your Node.js application.</p><p id="761d">It verifies that unprotected routes are accessible without a token, while protected routes require a valid token.</p><h1 id="1ac6">⚠️ Important Warning: Security Best Practices ⚠️</h1><p id="2230">In the code examples provided in this tutorial, we’ve used a hardcoded string <code>'secret_key'</code> as the secret to sign the JWT.</p><p id="912d">While this approach simplifies the tutorial, it should be noted that this is not secure for a production environment.</p><h2 id="cc10">Why is it a problem?</h2><p id="f45d">Hardcoding a secret key directly in your codebase can lead to several security risks:</p><ol><li><b>Exposure</b>: If your codebase is ever leaked or becomes public (for example, through a public GitHub repository), the hardcoded secret key will be visible to everyone.</li><li><b>Lack of Flexibility</b>: Hardcoding the key means it’s the same across all environments (development, staging, production). A breach in one environment could compromise all others.</li><li><b>Difficulty in Rotating Keys</b>: If you ever need to change the secret key, hardcoded values can make it a cumbersome process, especially if used in multiple places.</li></ol><h2 id="ac09">What should you do instead?</h2><ol><li><b>Use Environment Variables</b>: Store the secret key in an environment variable on the server where your application runs. This keeps the key out of your codebase and allows different keys for different environments.</li><li><b>Implement Key Rotation</b>: Consider implementing a strategy for rotating keys, ensuring that if a key is compromised, it can be quickly replaced without affecting users.</li><li><b>Leverage Secret Management Tools</b>: Tools like AWS Secrets Manager or HashiCorp Vault can manage, store, and control access to secret data, ensuring that sensitive information like secret keys is handled with the utmost security.</li></ol><h1 id="d203">Conclusion</h1><p id="c89f">JWT authentication is a powerful and straightforward way to secure your Node.js applications.</p><p id="303c">By following this guide, you have learned how JWT works, and how to generate, verify, and use JWT tokens in a Node.js application. The above example can be the foundation for more complex systems that require robust authentication and authorization mechanisms.</p><p id="c808">Remember that security is a multifaceted subject, and keeping up with best practices is crucial. Always consider additional security layers like HTTPS, OAuth2

Options

, etc., and stay updated with the latest industry standards.</p><p id="0bfb"><i>JWT and Authentication</i></p><ol><li><a href="https://jwt.io/"><i>JWT Official Website</i></a><i>: Learn more about JSON Web Tokens, including libraries, tools, and best practices.</i></li><li><a href="https://auth0.com/learn/json-web-tokens/"><i>Auth0’s Introduction to JWT</i></a><i>: A comprehensive guide by Auth0 that covers JWT’s structure, use cases, and more.</i></li></ol><p id="6edc"><i>Node.js and Express</i></p><ol><li><a href="https://nodejs.org/en/docs/"><i>Node.js Official Documentation</i></a><i>: Explore in-depth documentation on Node.js, from getting started to advanced topics.</i></li><li><a href="https://expressjs.com/"><i>Express.js Documentation</i></a><i>: Detailed information on how to use Express.js, a widely-used framework for Node.js.</i></li></ol><p id="5dcd"><i>API Testing Tools</i></p><ol><li><a href="https://learning.postman.com/"><i>Postman’s Learning Center</i></a><i>: Comprehensive guides and tutorials on using Postman for API testing.</i></li><li><a href="https://insomnia.rest/"><i>Insomnia</i></a><i>: An alternative to Postman, Insomnia offers a user-friendly interface for testing APIs.</i></li></ol><p id="f19e"><i>Additional Security Considerations</i></p><ol><li><a href="https://owasp.org/www-project-top-ten/"><i>OWASP Top Ten</i></a><i>: Familiarize yourself with the top ten security concerns for web applications, as outlined by the Open Web Application Security Project (OWASP).</i></li><li><a href="https://openid.net/connect/"><i>OAuth 2.0 and OpenID Connect</i></a><i>: For more advanced authentication and authorization mechanisms, learn about OAuth 2.0 and OpenID Connect.</i></li></ol><p id="4f60"><i>Tutorials and Courses</i></p><ol><li><a href="https://www.freecodecamp.org/learn/apis-and-microservices/"><i>FreeCodeCamp’s APIs and Microservices Certification</i></a><i>: FreeCodeCamp offers a free, in-depth curriculum for those wanting to understand APIs and microservices using Node.js.</i></li></ol><div id="49a6" class="link-block"> <a href="https://medium.com/@calebpr/subscribe"> <div> <div> <h2>Get an email whenever Caleb publishes.</h2> <div><h3>Get an email whenever Caleb publishes. By signing up, you will create a Medium account if you don’t already have one…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*pPSGj3ORvqLvuBYg)"></div> </div> </div> </a> </div><p id="91bd"><i>Enjoyed the read? For more on Web Development, JavaScript, Next.js, Cybersecurity, and Blockchain, check out my other articles here:</i></p><div id="7e3a" class="link-block"> <a href="https://readmedium.com/a-roadmap-to-my-medium-writings-fd04e14cffd7"> <div> <div> <h2>A Roadmap to My Medium Writings</h2> <div><h3>undefined</h3></div> <div><p>undefined</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*FO4S90VIpPA05s9cP-gFPQ.png)"></div> </div> </div> </a> </div><p id="8496"><i>If you have questions or feedback, don’t hesitate to reach out at [email protected] or in the comments section.</i></p><p id="c73a"><i>[Disclosure: Every article I pen is a fusion of my ideas and the supportive capabilities of artificial intelligence. While AI assists in refining and elaborating, the core thoughts and concepts stem from my perspective and knowledge. <a href="https://readmedium.com/how-does-ai-help-me-write-my-articles-5df265d16527">To know more about my creative process, read this article.</a>]</i></p><div id="a005" class="link-block"> <a href="https://readmedium.com/how-does-ai-help-me-write-my-articles-5df265d16527"> <div> <div> <h2>How Does AI Help Me Write My Articles?</h2> <div><h3>The Medium landscape has seen a transformation, with an increasing number of articles appearing to have the distinct…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*sURudlO3SS5ntthELFumcg.jpeg)"></div> </div> </div> </a> </div><h1 id="a196">In Plain English 🚀</h1><p id="a72c"><i>Thank you for being a part of the <a href="https://plainenglish.io/"><b>In Plain English</b></a> community! Before you go:</i></p><ul><li>Be sure to <b>clap</b> and <b>follow</b> the writer ️👏<b>️️</b></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><b>X</b></a><b> | <a href="https://www.linkedin.com/company/inplainenglish/">LinkedIn</a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw">YouTube</a> | <a href="https://discord.gg/in-plain-english-709094664682340443">Discord</a> | <a href="https://newsletter.plainenglish.io/">Newsletter</a></b></li><li>Visit our other platforms: <a href="https://stackademic.com/"><b>Stackademic</b></a><b> | <a href="https://cofeed.app/">CoFeed</a> | <a href="https://venturemagazine.net/">Venture</a> | <a href="https://blog.cubed.run/">Cubed</a></b></li><li>More content at <a href="https://plainenglish.io/"><b>PlainEnglish.io</b></a></li></ul></article></body>

How to Integrate JWT Into Your Node.js App: A Step-by-Step Tutorial

In this step-by-step tutorial, we’ll explore how to integrate JWT authentication into a Node.js application, even if you’re just starting out with Node.js

Security is a paramount concern in the digital world, and when it comes to authentication, the JSON Web Token (JWT) has become the industry standard.

In this step-by-step tutorial, we’ll explore how to integrate JWT authentication into a Node.js application, even if you’re just starting out with Node.js.

Let’s dive in and uncover the secrets of secure, scalable authentication!

Part 1: Understanding JWT

What is JWT?

JSON Web Token (JWT) is an open standard that defines a compact and self-contained way of securely transmitting information between parties as a JSON object.

This information can be verified and trusted because it is digitally signed.

Structure of a JWT

A JWT typically looks like xxxxx.yyyyy.zzzzz and is divided into three parts:

  1. Header: Encodes the token type and the algorithm used.
  2. Payload: Contains the claims, which are statements about an entity (e.g., user details).
  3. Signature: Validates the token.

Part 2: Setting Up the Project

Step 1: Create a New Node.js Project

mkdir my-jwt-app
cd my-jwt-app
npm init -y

Step 2: Install the Required Dependencies

npm install express jsonwebtoken

Part 3: Implementing JWT Authentication

Step 1: Creating a Simple Express Server

const express = require('express');
const app = express();

app.use(express.json());

app.get('/', (req, res) => {
  res.send('Welcome to the JWT Tutorial');
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Step 2: Generating a JWT Token

We’ll simulate a simple login endpoint to generate a JWT.

const jwt = require('jsonwebtoken');

app.post('/login', (req, res) => {
  const user = { id: 3 }; // Example user
  const token = jwt.sign({ user }, 'secret_key', { expiresIn: '1h' });
  res.json({ token });
});

Step 3: Verifying a JWT Token

Now we’ll create a middleware to validate the token on protected routes.

function verifyToken(req, res, next) {
  const bearerHeader = req.headers['authorization'];
  if (typeof bearerHeader !== 'undefined') {
    const token = bearerHeader.split(' ')[1];
    jwt.verify(token, 'secret_key', (err, authData) => {
      if (err) {
        res.sendStatus(403);
      } else {
        req.user = authData;
        next();
      }
    });
  } else {
    res.sendStatus(403);
  }
}

// Protected route
app.get('/protected', verifyToken, (req, res) => {
  res.json({ message: 'Protected route accessed!', user: req.user });
});

Part 4: Testing JWT-Protected Endpoints

After implementing JWT authentication, it’s vital to ensure that our endpoints are working as expected.

Testing can be done through a web browser for open routes or using tools like Postman for the secured endpoints.

Here’s how you can test the authentication flow:

Step 1: Testing the Unprotected Route in a Browser

You can simply open your web browser and navigate to http://localhost:3000/. You should see the welcome message: "Welcome to the JWT Tutorial."

Step 2: Testing the Login and Protected Endpoints Using Postman

Postman is a popular tool for testing APIs. Follow these steps to test the login and protected routes:

  1. Testing the Login Endpoint
  • Open Postman.
  • Set the request method to POST.
  • Enter the URL http://localhost:3000/login.
  • Click “Send” to make the request.
  • You should receive a JSON response containing the token.

2. Testing the Protected Endpoint with the Token

  • Copy the token from the login response.
  • Create a new request in Postman.
  • Set the request method to GET.
  • Enter the URL http://localhost:3000/protected.
  • Under the “Headers” tab, or directly under the “Authorization” tab, add a key Authorization with the value Bearer YOUR_TOKEN (replace YOUR_TOKEN with the copied token).
  • Click “Send” to make the request.
  • You should receive a JSON response with the message “Protected route accessed!” and the user details.

3. Testing the Protected Endpoint without the Token or with an Invalid Token

  • Repeat the steps for the protected endpoint but omit the token or use an invalid one.
  • You should receive a 403 status code, indicating that access is forbidden.

By following these steps, you’ve ensured that the JWT authentication is correctly implemented in your Node.js application.

It verifies that unprotected routes are accessible without a token, while protected routes require a valid token.

⚠️ Important Warning: Security Best Practices ⚠️

In the code examples provided in this tutorial, we’ve used a hardcoded string 'secret_key' as the secret to sign the JWT.

While this approach simplifies the tutorial, it should be noted that this is not secure for a production environment.

Why is it a problem?

Hardcoding a secret key directly in your codebase can lead to several security risks:

  1. Exposure: If your codebase is ever leaked or becomes public (for example, through a public GitHub repository), the hardcoded secret key will be visible to everyone.
  2. Lack of Flexibility: Hardcoding the key means it’s the same across all environments (development, staging, production). A breach in one environment could compromise all others.
  3. Difficulty in Rotating Keys: If you ever need to change the secret key, hardcoded values can make it a cumbersome process, especially if used in multiple places.

What should you do instead?

  1. Use Environment Variables: Store the secret key in an environment variable on the server where your application runs. This keeps the key out of your codebase and allows different keys for different environments.
  2. Implement Key Rotation: Consider implementing a strategy for rotating keys, ensuring that if a key is compromised, it can be quickly replaced without affecting users.
  3. Leverage Secret Management Tools: Tools like AWS Secrets Manager or HashiCorp Vault can manage, store, and control access to secret data, ensuring that sensitive information like secret keys is handled with the utmost security.

Conclusion

JWT authentication is a powerful and straightforward way to secure your Node.js applications.

By following this guide, you have learned how JWT works, and how to generate, verify, and use JWT tokens in a Node.js application. The above example can be the foundation for more complex systems that require robust authentication and authorization mechanisms.

Remember that security is a multifaceted subject, and keeping up with best practices is crucial. Always consider additional security layers like HTTPS, OAuth2, etc., and stay updated with the latest industry standards.

JWT and Authentication

  1. JWT Official Website: Learn more about JSON Web Tokens, including libraries, tools, and best practices.
  2. Auth0’s Introduction to JWT: A comprehensive guide by Auth0 that covers JWT’s structure, use cases, and more.

Node.js and Express

  1. Node.js Official Documentation: Explore in-depth documentation on Node.js, from getting started to advanced topics.
  2. Express.js Documentation: Detailed information on how to use Express.js, a widely-used framework for Node.js.

API Testing Tools

  1. Postman’s Learning Center: Comprehensive guides and tutorials on using Postman for API testing.
  2. Insomnia: An alternative to Postman, Insomnia offers a user-friendly interface for testing APIs.

Additional Security Considerations

  1. OWASP Top Ten: Familiarize yourself with the top ten security concerns for web applications, as outlined by the Open Web Application Security Project (OWASP).
  2. OAuth 2.0 and OpenID Connect: For more advanced authentication and authorization mechanisms, learn about OAuth 2.0 and OpenID Connect.

Tutorials and Courses

  1. FreeCodeCamp’s APIs and Microservices Certification: FreeCodeCamp offers a free, in-depth curriculum for those wanting to understand APIs and microservices using Node.js.

Enjoyed the read? For more on Web Development, JavaScript, Next.js, Cybersecurity, and Blockchain, check out my other articles here:

If you have questions or feedback, don’t hesitate to reach out at [email protected] or in the comments section.

[Disclosure: Every article I pen is a fusion of my ideas and the supportive capabilities of artificial intelligence. While AI assists in refining and elaborating, the core thoughts and concepts stem from my perspective and knowledge. To know more about my creative process, read this article.]

In Plain English 🚀

Thank you for being a part of the In Plain English community! Before you go:

JavaScript
Programming
Web Development
Startup
Technology
Recommended from ReadMedium