This document describes the secure session management implementation for the wallet authentication system.
The application now includes a comprehensive secure session management system with the following features:
-
Secure Session Configuration
HttpOnlycookies to prevent JavaScript accessSameSite=Laxfor CSRF protection- Strict session mode to reject uninitialized session IDs
- Session cookie lifetime of 1 hour
- Session timeout after 30 minutes of inactivity
-
Session Validation
- Session timeout checking (30 minutes of inactivity)
- User-Agent validation to detect session hijacking
- Optional IP address validation (commented out by default due to mobile user issues)
-
CSRF Protection
- CSRF tokens generated on login
- Token validation helpers available
-
Session Regeneration
- Session ID regenerated on login to prevent session fixation attacks
-
Secure Token Generation
- Uses
random_bytes(32)for cryptographically secure token generation
- Uses
Enhanced wallet login handler with secure session configuration:
- Secure session settings
- Session regeneration on login
- CSRF token generation
- Improved logging with session ID
Session management utility library with functions:
startSecureSession()- Initialize secure sessionisAuthenticated()- Check if user is authenticatedcheckSessionTimeout()- Validate session hasn't expiredvalidateSessionSecurity()- Check for session hijackingrequireAuthentication($loginUrl)- Require auth or redirectgetUserWalletInfo()- Get current user's wallet infodestroySession()- Destroy session completelylogout($redirectUrl)- Log out uservalidateCsrfToken($token)- Validate CSRF tokengetCsrfToken()- Get current CSRF token
Example protected page that demonstrates:
- Authentication requirement
- Automatic redirect to login for unauthenticated users
- Display of wallet and session information
- Logout functionality
Logout endpoint that:
- Destroys the session
- Clears session cookies
- Returns JSON response
Session status endpoint for frontend:
- Returns authentication status
- Returns user wallet info if authenticated
- Used for client-side session validation
Enhanced Apache configuration:
- Security headers (X-Frame-Options, X-XSS-Protection, etc.)
- Denies direct access to session.php
- Denies access to log files
- Prevents directory listing
<?php
require_once 'session.php';
// Require authentication - redirects to /index.html if not authenticated
requireAuthentication('/index.html');
// Get user info
$walletInfo = getUserWalletInfo();
echo "Welcome, " . $walletInfo['address'];
?>async function checkSession() {
const response = await fetch('/check-session.php', {
credentials: 'include'
});
const data = await response.json();
return data.authenticated;
}async function logout() {
await fetch('/logout.php', {
method: 'POST',
credentials: 'include'
});
window.location.href = '/index.html';
}Edit SESSION_TIMEOUT in /public/session.php (default: 1800 seconds = 30 minutes)
For production with HTTPS, update in both files:
ini_set('session.cookie_secure', 1); // Require HTTPSUpdate the Access-Control-Allow-Origin header in all PHP files:
header('Access-Control-Allow-Origin: https://yourdomain.com');To enable IP checking (may cause issues with mobile users), uncomment in session.php:
if (isset($_SESSION['ip_address'])) {
$currentIp = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
if ($_SESSION['ip_address'] !== $currentIp) {
return false;
}
}-
Test Login Flow
- Visit the app at
http://localhost:3000 - Connect your wallet
- Visit
http://localhost:3000/dashboard.php - Verify you can see your wallet info
- Visit the app at
-
Test Authentication Requirement
- Clear cookies/use incognito mode
- Try to access
http://localhost:3000/dashboard.phpdirectly - Verify you're redirected to login
-
Test Session Timeout
- Log in and wait 30 minutes
- Try to access dashboard
- Verify you're redirected to login
-
Test Logout
- Log in and access dashboard
- Click logout button
- Try to access dashboard again
- Verify you're redirected to login
-
HTTPS in Production: Always use HTTPS in production and set
session.cookie_secure = 1 -
CORS Configuration: Update
Access-Control-Allow-Originfrom*to your specific domain -
Database Integration: For production, store sessions in a database instead of file system
-
Rate Limiting: Implement rate limiting on login.php to prevent brute force attacks
-
Logging: Store logs outside the web root (e.g.,
/var/log/app/) -
Error Handling: Don't expose sensitive information in error messages
-
Input Validation: All user inputs are validated before processing
- Add remember me functionality with long-lived tokens
- Implement multi-factor authentication
- Add session activity logging
- Implement account lockout after failed attempts
- Add email notifications for new logins
- Store sessions in Redis/Memcached for scalability
- Add JWT tokens for API authentication
- Implement refresh token mechanism