Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Storing Credentials in Local Storage
Local Storage is designed for data that spans multiple windows and persists beyond the current session. Web applications can store megabytes of user data on the client side for performance reasons. However, storing credentials requires special security considerations.
For secure credential storage, never store actual passwords or sensitive authentication data directly in local storage. Instead, use a token-based approach that minimizes security risks.
Secure Token-Based Authentication
On successful login, generate a completely random token string unrelated to user credentials. Store this token in your database with an expiry date, then pass it to JavaScript for local storage.
<!DOCTYPE html>
<html>
<head>
<title>Secure Login Example</title>
</head>
<body>
<div id="loginForm">
<input type="text" id="username" placeholder="Username">
<input type="password" id="password" placeholder="Password">
<button onclick="login()">Login</button>
</div>
<div id="userArea" style="display:none;">
<p>Welcome! You are logged in.</p>
<button onclick="logout()">Logout</button>
</div>
<script>
// Simulate login process
function login() {
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
// In real app, validate credentials on server
if (username && password) {
// Server would generate random token
const authToken = generateRandomToken();
const expiryTime = Date.now() + (24 * 60 * 60 * 1000); // 24 hours
// Store token with expiry
const authData = {
token: authToken,
expiry: expiryTime,
username: username
};
localStorage.setItem('authData', JSON.stringify(authData));
showUserArea();
}
}
function generateRandomToken() {
return Math.random().toString(36).substring(2) +
Math.random().toString(36).substring(2);
}
function isValidSession() {
const authData = localStorage.getItem('authData');
if (!authData) return false;
const parsed = JSON.parse(authData);
return Date.now() < parsed.expiry;
}
function logout() {
localStorage.removeItem('authData');
showLoginForm();
}
function showUserArea() {
document.getElementById('loginForm').style.display = 'none';
document.getElementById('userArea').style.display = 'block';
}
function showLoginForm() {
document.getElementById('loginForm').style.display = 'block';
document.getElementById('userArea').style.display = 'none';
}
// Check session on page load
if (isValidSession()) {
showUserArea();
}
</script>
</body>
</html>
Token Validation Process
As long as the local storage token matches the database record and hasn't expired, consider the user authenticated:
<script>
function validateToken() {
const authData = localStorage.getItem('authData');
if (!authData) {
console.log('No auth data found');
return false;
}
const parsed = JSON.parse(authData);
const currentTime = Date.now();
if (currentTime > parsed.expiry) {
console.log('Token expired');
localStorage.removeItem('authData');
return false;
}
console.log('Valid session found');
return true;
}
// Example usage
if (validateToken()) {
console.log('User is authenticated');
} else {
console.log('User needs to log in');
}
</script>
Security Benefits
| Approach | Security Risk | Data Exposed |
|---|---|---|
| Direct Password Storage | High | User credentials |
| Random Token with Expiry | Low | Temporary access only |
Best Practices
Always set token expiry dates, use HTTPS for token transmission, and implement proper server-side validation. Consider using shorter expiry times for sensitive applications.
Conclusion
This token-based approach ensures no actual user credentials are exposed in local storage. The random token provides secure authentication while maintaining user sessions across browser windows.
