🔧 AI Nachrichten Major AI platforms go down in unprecedented simultaneous outage(03.09.2026 um 17:34 Uhr)
🔧 AI Nachrichten ChatGPT, Claude, and Grok Down? Users Report Widespread Outages(03.09.2026 um 19:14 Uhr)
🔧 AI Nachrichten OpenAI Launches GPT-6 Astra, Says We May Have Entered the AGI Era(03.09.2026 um 22:08 Uhr)
🔧 AI Nachrichten Claude Comes to CarPlay as Fifth Major AI Chatbot App(05.09.2026 um 05:31 Uhr)
🔧 AI Nachrichten OpenAI’s GPT-6 Astra Is AGI, Says NVIDIA CEO Jensen Huang(07.09.2026 um 06:31 Uhr)
🔧 AI Nachrichten Blame AI companies for Mac mini and Mac Studio shortage(31.08.2026 um 10:32 Uhr)
🔧 AI Nachrichten Major AI platforms go down in unprecedented simultaneous outage(03.09.2026 um 17:34 Uhr)
🔧 AI Nachrichten ChatGPT, Claude, and Grok Down? Users Report Widespread Outages(03.09.2026 um 19:14 Uhr)
🔧 AI Nachrichten OpenAI Launches GPT-6 Astra, Says We May Have Entered the AGI Era(03.09.2026 um 22:08 Uhr)
🔧 AI Nachrichten Claude Comes to CarPlay as Fifth Major AI Chatbot App(05.09.2026 um 05:31 Uhr)
🔧 AI Nachrichten OpenAI’s GPT-6 Astra Is AGI, Says NVIDIA CEO Jensen Huang(07.09.2026 um 06:31 Uhr)
🔧 AI Nachrichten Blame AI companies for Mac mini and Mac Studio shortage(31.08.2026 um 10:32 Uhr)

🔧 Programmierung 🕛 kürzlich 4 Min Lesezeit
0

Creating and Securing JWT Authentication in a Web App

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht




Introduction



JSON Web Tokens (JWT) are a compact and self-contained way of securely transmitting information between parties as a JSON object. JWTs are widely used for authenticating users in web applications. In this tutorial, we’ll build a Node.js and Express backend with JWT authentication.






What is JWT?



JWT (JSON Web Token) is an open standard for securely transmitting information between parties as a JSON object. Each token consists of three parts:




  1. Header: Contains information about the token's type and hashing algorithm.

  2. Payload: Contains user information and claims.

  3. Signature: Verifies the integrity of the token.






Example JWT






CODE
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjM0IiwidXNlcm5hbWUiOiJqb2huZG9lIn0.H6BBiB1y5eXKXvW9bbjT2Rg8Jp4oE4Y5Kxf_sDF7Kzg









Setting Up the Project





  1. Create a new project directory:


    CODE
    mkdir jwt-auth-app
    cd jwt-auth-app




  2. Initialize a new Node.js project:


    CODE
    npm init -y








Installing Dependencies



Install the necessary dependencies:




CODE
npm install express jsonwebtoken bcryptjs dotenv express-validator







  • express: Web framework for Node.js.

  • jsonwebtoken: Library for generating and verifying JWTs.

  • bcryptjs: Library for hashing passwords.

  • dotenv: For environment variables.

  • express-validator: For validating input data.






Configuring the Server



Create a basic server setup in server.js:




CODE
// server.js
require('dotenv').config();
const express = require('express');
const app = express();
app.use(express.json());

// Import Routes
const authRoutes = require('./routes/auth');
app.use('/api/auth', authRoutes);

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));






Create a .env file for storing environment variables:




CODE
PORT=5000
JWT_SECRET=your_jwt_secret_key









Creating User Authentication Routes




  1. Create the routes/auth.js file for authentication routes:




CODE
// routes/auth.js
const express = require('express');
const { body, validationResult } = require('express-validator');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const router = express.Router();

const users = []; // In-memory user storage

// Signup Route
router.post(
'/signup',
[
body('username').isLength({ min: 3 }),
body('password').isLength({ min: 5 })
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() });

const { username, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);

users.push({ username, password: hashedPassword });
res.status(201).json({ message: 'User registered successfully' });
}
);

// Login Route
router.post(
'/login',
[
body('username').notEmpty(),
body('password').notEmpty()
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() });

const { username, password } = req.body;
const user = users.find(u => u.username === username);

if (!user) return res.status(400).json({ message: 'Invalid credentials' });

const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) return res.status(400).json({ message: 'Invalid credentials' });

const token = jwt.sign({ username }, process.env.JWT_SECRET, { expiresIn: '1h' });
res.json({ token });
}
);

module.exports = router;







  1. Explanation of Routes




  • Signup Route: Validates and hashes the password before storing the user.

  • Login Route: Validates credentials, checks password, and issues a JWT token.






Generating JWT Tokens




  • The jwt.sign method generates a token containing the user’s information.

  • The JWT_SECRET is used to sign the token, which should be kept secure and private.




CODE
const token = jwt.sign({ username }, process.env.JWT_SECRET, { expiresIn: '1h' });









Securing Routes with JWT



To protect routes, create a middleware to verify tokens.




  1. Create middleware/auth.js:




CODE
// middleware/auth.js
const jwt = require('jsonwebtoken');

module.exports = function (req, res, next) {
const token = req.header('Authorization')?.split(' ')[1];
if (!token) return res.status(401).json({ message: 'Access denied' });

try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (ex) {
res.status(400).json({ message: 'Invalid token' });
}
};







  1. Protect Routes in server.js:



Create a protected route that requires a valid token:




CODE
// In server.js
const authMiddleware = require('./middleware/auth');

app.get('/api/protected', authMiddleware, (req, res) => {
res.json({ message: 'This is a protected route', user: req.user });
});









Explanation of Middleware




  • The middleware checks for the presence of the token in the Authorization header.

  • If the token is valid, the user’s information is added to the req object, allowing access to the protected route.






Conclusion



In this tutorial, we’ve covered the basics of setting up JWT authentication in a Node.js and Express backend. This guide demonstrated:




  1. Setting up authentication routes for signup and login.

  2. Creating and verifying JWT tokens.

  3. Securing routes with a JWT-based middleware.



JWTs are a powerful way to handle authentication, making your web applications both secure and scalable.

Vollständiger Original-Bericht
Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
3 Quellen
GPT-6 Astra Release Today? OpenAI’s Next Major AI Model Is Almost Here
1 Quelle
Apple accuses OpenAI of destroying evidence as trade-secrets fight intensifies
1 Quelle
Major AI platforms go down in unprecedented simultaneous outage
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Creating and Securing JWT Authentication in a Web App

Thematisch verwandte Begriffe: Creating, Securing, Authentication · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...