登录后JWT Token存储、页面跳转及受保护路由鉴权技术咨询
Hey there, let's walk through each of your JWT-related questions step by step with actionable code examples that fit your existing setup.
1. Redirect to Protected URL After Storing Token
Once you've successfully saved the token to localStorage, you can use browser navigation APIs to jump to your protected page. Just make sure you only do this after confirming the token was generated and stored correctly (handle any errors from the login API first).
Frontend Login Code Example (using Fetch API):
// Login form submission handler document.getElementById('login-form').addEventListener('submit', async (e) => { e.preventDefault(); const username = document.getElementById('username').value; const password = document.getElementById('password').value; try { const response = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }); const data = await response.json(); if (data.token) { // Save token to localStorage localStorage.setItem('token', data.token); // Redirect to protected admin page window.location.href = '/admin/admin.html'; } else { alert('Login failed: No token received'); } } catch (err) { console.error('Login error:', err); alert('Login failed, please try again'); } });
2. Use Stored Token in Protected Routes
In your protected pages (like /admin/admin.html), you'll need to:
- First check if the token exists in
localStorage(if not, redirect back to login) - Include the token in the
Authorizationheader of every request to your protected backend APIs
Example: Protected Page Initialization + API Request
// On page load of admin.html document.addEventListener('DOMContentLoaded', () => { const token = localStorage.getItem('token'); if (!token) { // No token found, redirect to login window.location.href = '/login.html'; return; } // Example: Fetch admin data using the token fetch('/api/admin/dashboard', { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` // Attach token here } }) .then(response => { if (!response.ok) { throw new Error('Unauthorized'); } return response.json(); }) .then(data => { // Render admin dashboard with data document.getElementById('dashboard-content').textContent = JSON.stringify(data); }) .catch(err => { console.error('API error:', err); // If token is invalid/expired, clear storage and redirect to login localStorage.removeItem('token'); window.location.href = '/login.html'; }); });
3. Verify User Consistency Between Token and Current Visitor
You don't need to submit user info every time to compare with the token. Instead:
- Backend: Use a middleware to verify the token, decode it to get the embedded
userdata, and attach that user info to the request object. All protected APIs can then use this attached user info to ensure the request is valid for that user. - Frontend (optional): If you need to display user info or do quick client-side checks, you can decode the token (without verifying the signature—always rely on backend for actual validation) to get the
userdata.
Backend Token Verification Middleware (Node.js/Express example):
const jwt = require('jsonwebtoken'); const secretKey = 'your-secret-key-here'; // Use environment variables in production // Middleware to protect routes const authenticateToken = (req, res, next) => { // Get token from Authorization header const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; // Extract "Bearer <token>" if (!token) { return res.status(401).json({ message: 'No token provided' }); } // Verify and decode token jwt.verify(token, secretKey, (err, user) => { if (err) { return res.status(403).json({ message: 'Invalid or expired token' }); } // Attach decoded user data to request object req.user = user; next(); // Proceed to the protected route handler }); }; // Example protected route using the middleware app.get('/api/admin/dashboard', authenticateToken, (req, res) => { // req.user contains the userdata from the token // You can use this to fetch user-specific admin data res.json({ message: `Welcome back, ${req.user.username}!`, userData: req.user }); });
Frontend Client-Side Token Decoding (for display only):
// Helper function to decode token (no signature verification) const decodeToken = (token) => { try { return JSON.parse(atob(token.split('.')[1])); // Decode the payload } catch (err) { return null; } }; // In admin.html const token = localStorage.getItem('token'); const decodedUser = decodeToken(token); if (decodedUser) { document.getElementById('welcome-message').textContent = `Welcome, ${decodedUser.username}!`; }
Important: Client-side decoding is only for UI purposes—never trust client-side validation. Always rely on the backend middleware to verify the token's authenticity and user identity.
内容的提问来源于stack exchange,提问作者Ronald Tan

