Skip to main content
coding intermediate

Implement JWT Authentication System

Get step-by-step JWT authentication implementation with secure best practices. Complete code examples for any framework or language.

Works with: chatgptclaudegemini

Prompt Template

I need you to implement a complete JWT (JSON Web Token) authentication system for my [PROGRAMMING_LANGUAGE] application using [FRAMEWORK]. Please provide a comprehensive solution that includes: 1. **Token Generation**: Create a secure JWT token generation function that includes user identification, expiration time, and proper signing with a secret key. 2. **Token Validation**: Implement middleware or functions to validate incoming JWT tokens, check expiration, verify signatures, and handle invalid tokens gracefully. 3. **Authentication Flow**: Show the complete authentication process including: - User login endpoint that validates credentials and returns a JWT - Protected route middleware that requires valid JWT - Token refresh mechanism (if applicable) - Logout functionality 4. **Security Best Practices**: Ensure the implementation follows security best practices including: - Proper secret key management - Secure token storage recommendations - Protection against common JWT vulnerabilities - Appropriate token expiration times 5. **Error Handling**: Include comprehensive error handling for scenarios like expired tokens, invalid signatures, malformed tokens, and missing tokens. 6. **Code Examples**: Provide complete, working code examples with comments explaining each part. Please structure the response with clear sections for each component and include usage examples showing how to integrate this authentication system into my application. Focus on [SPECIFIC_USE_CASE] requirements.

Variables to Customize

[PROGRAMMING_LANGUAGE]

The programming language you want to implement JWT auth in

Example: Node.js

[FRAMEWORK]

The specific framework or library you're using

Example: Express.js

[SPECIFIC_USE_CASE]

Your specific application type or requirements

Example: REST API for a mobile app

Example Output

# JWT Authentication Implementation for Node.js/Express.js ## 1. Dependencies and Setup ```javascript const jwt = require('jsonwebtoken'); const bcrypt = require('bcrypt'); const express = require('express'); const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key'; const JWT_EXPIRES_IN = '24h'; ``` ## 2. Token Generation ```javascript function generateToken(userId, email) { return jwt.sign( { userId, email }, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN } ); } ``` ## 3. Authentication Middleware ```javascript const authenticateToken = (req, res, next) => { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; if (!token) { return res.status(401).json({ error: 'Access token required' }); } jwt.verify(token, JWT_SECRET, (err, user) => { if (err) { return res.status(403).json({ error: 'Invalid or expired token' }); } req.user = user; next(); }); }; ``` ## 4. Login Endpoint ```javascript app.post('/login', async (req, res) => { try { const { email, password } = req.body; // Validate user credentials (check against database) const user = await validateUser(email, password); if (!user) { return res.status(401).json({ error: 'Invalid credentials' }); } const token = generateToken(user.id, user.email); res.json({ token, user: { id: user.id, email: user.email } }); } catch (error) { res.status(500).json({ error: 'Server error' }); } }); ``` This implementation provides secure JWT authentication with proper error handling and follows security best practices for REST API applications.

Pro Tips for Best Results

  • Always use environment variables to store your JWT secret key - never hardcode it in your source code
  • Set appropriate token expiration times - shorter for sensitive applications (15-30 minutes) with refresh tokens
  • Implement token blacklisting for logout functionality to prevent token reuse
  • Use HTTPS in production to prevent token interception during transmission
  • Consider implementing rate limiting on authentication endpoints to prevent brute force attacks

Tags

Want 500+ Expert Prompts?

Get the Premium Prompt Pack — organized, tested, and ready to use.

Get it for $29

Related Prompts You Might Like