Session hijacking is a security threat where an attacker steals a user’s session ID to impersonate them and gain unauthorized access. Since AngularJS primarily runs on the client side, session management is handled at the backend, but proper security measures in both frontend and backend are crucial to prevent session hijacking.
This guide covers:
- How Session Hijacking Works
- Best Practices for Securing Sessions in AngularJS
- Use Secure and HttpOnly Cookies
- Implement Session Expiry and Auto-Logout
- Enable HTTPS and Secure Cookies
- Use JSON Web Tokens (JWT) with Refresh Tokens
- Prevent Cross-Site Scripting (XSS)
- Prevent Cross-Site Request Forgery (CSRF)
- Implement IP Binding and User-Agent Tracking
- Detect and Invalidate Stolen Sessions
- Implementing Session Security in AngularJS
- Testing Session Security
- Best Practices for Continuous Security
1. How Session Hijacking Works?
Attackers can hijack a session using methods like:
- Session Fixation: Attacker forces the victim to use a predefined session ID.
- Man-in-the-Middle (MITM) Attack: Session data is intercepted over an unsecured connection.
- Cross-Site Scripting (XSS): Malicious scripts steal session tokens.
- Session Sidejacking: Attackers sniff session cookies over an unsecured network.
2. Best Practices for Securing Sessions in AngularJS
1️⃣ Use Secure and HttpOnly Cookies
Instead of storing session tokens in localStorage or sessionStorage, use HttpOnly cookies to prevent JavaScript-based theft.
Server-Side (Node.js Express Example):
app.use(require('cookie-parser')());
app.use(session({
secret: 'your-secure-secret',
resave: false,
saveUninitialized: true,
cookie: { secure: true, httpOnly: true, sameSite: 'Strict' }
}));
🔹 HttpOnly: Prevents JavaScript from accessing cookies (stops XSS attacks).
🔹 Secure: Ensures cookies are only sent over HTTPS.
🔹 sameSite=’Strict’: Prevents cookies from being sent with cross-site requests.
2️⃣ Implement Session Expiry and Auto-Logout
Set an expiration time for sessions and auto-logout users after inactivity.
Example: Set Session Expiry in Express:
app.use(session({
secret: 'your-secure-secret',
cookie: { maxAge: 30 * 60 * 1000 } // 30 minutes expiry
}));
AngularJS Auto-Logout on Inactivity:
app.run(function($rootScope, $timeout, AuthService) {
let logoutTimer;
function resetTimer() {
if (logoutTimer) $timeout.cancel(logoutTimer);
logoutTimer = $timeout(() => AuthService.logout(), 1800000); // Auto logout after 30 mins
}
angular.element(document).on('mousemove keydown', resetTimer);
resetTimer();
});
Logs out users automatically after 30 minutes of inactivity.
3️⃣ Enforce HTTPS and Secure Cookies
Ensure your app forces HTTPS and uses secure cookies.
Enable HTTPS in Express:
const fs = require('fs');
const https = require('https');
const options = {
key: fs.readFileSync('private.key'),
cert: fs.readFileSync('certificate.crt')
};
https.createServer(options, app).listen(443, () => {
console.log('Secure Server Running on Port 443');
});
Why? Prevents MITM attacks and cookie sniffing.
4️⃣ Use JSON Web Tokens (JWT) with Refresh Tokens
JWT is a more secure alternative to traditional session IDs.
Backend (Express Example):
const jwt = require('jsonwebtoken');
app.post('/login', (req, res) => {
const user = { id: req.body.id };
const accessToken = jwt.sign(user, process.env.ACCESS_SECRET, { expiresIn: '15m' });
const refreshToken = jwt.sign(user, process.env.REFRESH_SECRET);
res.cookie('token', accessToken, { httpOnly: true, secure: true, sameSite: 'Strict' });
res.json({ refreshToken });
});
🔹 Benefits:
✔ Short-lived tokens reduce risk if stolen.
✔ Refresh tokens avoid frequent logins.
✔ HttpOnly cookie prevents XSS-based theft.
5️⃣ Prevent Cross-Site Scripting (XSS)
XSS allows attackers to steal session tokens.
Use AngularJS $sanitize to clean user input:
<input type="text" ng-model="userInput">
<p ng-bind-html="userInput | sanitize"></p>
Set Content Security Policy (CSP) in meta tag:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
🔹 Prevents: Injection of malicious scripts.
6️⃣ Prevent Cross-Site Request Forgery (CSRF)
CSRF tricks users into submitting requests on their behalf.
Enable CSRF Protection in Express (Backend):
const csrf = require('csurf');
app.use(csrf({ cookie: true }));
AngularJS $http Setup:
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'XSRF-TOKEN';
$httpProvider.defaults.xsrfHeaderName = 'X-XSRF-TOKEN';
}]);
Prevents: Unauthorized requests from malicious websites.
7️⃣ Implement IP Binding and User-Agent Tracking
Validate sessions by binding them to the user’s IP address and browser.
Track IP & User-Agent in Express:
app.use((req, res, next) => {
const userSession = sessions[req.sessionID];
if (userSession && userSession.ip !== req.ip) {
req.session.destroy();
return res.status(401).json({ error: 'Session hijacked!' });
}
next();
});
Terminates session if accessed from a different IP.
8️⃣ Detect and Invalidate Stolen Sessions
Monitor for unusual session behavior.
Use Middleware to Log Session Activity:
app.use((req, res, next) => {
console.log(`Session ID: ${req.sessionID}, IP: ${req.ip}, Time: ${new Date()}`);
next();
});
🔹 Detects session anomalies in logs.
3. Testing Session Security
1. Check Cookies in DevTools
- Open Chrome DevTools (F12) → Application Tab.
- Navigate to Storage → Cookies → Verify
HttpOnly,Secure,SameSite=Strict.
2. Use Curl to Inspect Cookies
curl -I https://yourapp.com
🔹 Check if Set-Cookie has Secure, HttpOnly, and SameSite attributes.
3. Test XSS Attack Attempts
Try injecting scripts in input fields:
<script>alert('XSS')</script>
Should not execute if CSP and $sanitize are enabled.
