Skip to content

A simple implementation of JWT (JSON Web Token) authentication in Node.js using Express. This project demonstrates generating JWTs, validating tokens via middleware, and securing protected routes. Perfect for learning authentication basics!

Notifications You must be signed in to change notification settings

DevRelSquad-blogs/JWT_Explained

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Simple JWT Authentication Demo

A basic demonstration of JWT (JSON Web Token) authentication using Express.js. This project shows how to implement token-based authentication with protected routes.

🚀 Features

  • Basic JWT authentication
  • Protected route example
  • Express.js REST API
  • Simple token verification middleware

🛠️ Installation

# Clone the repository
git clone <your-repo-url>

# Install dependencies
npm install express jsonwebtoken body-parser

🔧 Environment Setup

Create a .env file in the root directory:

JWT_SECRET=your_secret_key
PORT=3000

🏃‍♂️ Quick Start

# Start the server
node server.js

🔍 API Endpoints

Authentication

POST /login
- Generates JWT token
- Body: { "username": "your_username" }

Protected Route

GET /protected
- Requires JWT token in Authorization header
- Returns protected data

📝 Usage Example

Login and Get Token

fetch('http://localhost:3000/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    username: 'testuser'
  })
})
.then(res => res.json())
.then(data => console.log(data.token));

Access Protected Route

fetch('http://localhost:3000/protected', {
  headers: {
    'Authorization': 'Bearer YOUR_JWT_TOKEN'
  }
})
.then(res => res.json())
.then(data => console.log(data));

🔒 Security Note

In production:

  • Use a strong secret key
  • Store sensitive data in environment variables
  • Implement proper error handling
  • Add input validation

About

A simple implementation of JWT (JSON Web Token) authentication in Node.js using Express. This project demonstrates generating JWTs, validating tokens via middleware, and securing protected routes. Perfect for learning authentication basics!

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published