Insecure Client-Side Storage of JWTs
Concept
Vulnerable Scenario
Example Code (Vulnerable)
// Backend code (Express.js)
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
app.use(express.json());
const secretKey = 'your-secret-key';
app.post('/login', (req, res) => {
const { username, password } = req.body;
// Authenticate the user (code not shown)
if (authenticateUser(username, password)) {
const token = jwt.sign({ username }, secretKey);
res.json({ token });
} else {
res.status(401).json({ message: 'Invalid credentials' });
}
});
// Frontend code (HTML and JavaScript)
<!DOCTYPE html>
<html>
<head>
<title>Welcome User</title>
<script>
// Get the JWT token from local storage
const token = localStorage.getItem('token');
// Use the token to make authenticated requests
fetch('/api/protected', {
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(response => response.json())
.then(data => {
document.getElementById('welcome').textContent = data.message;
});
</script>
</head>
<body>
<h1 id="welcome"></h1>
</body>
</html>Explanation
Prevention
Conclusion
Semgrep Rules
Last updated