Session management is a crucial aspect of securing an AngularJS application. It ensures that user sessions are protected from attacks like session hijacking, fixation, and cross-site scripting (XSS).
1. Key Aspects of Secure Session Management
✔ Storing Sessions Securely – Avoid using localStorage for sensitive data
✔ Session Timeout Handling – Automatically log users out after inactivity
✔ Token-Based Authentication – Use JWT instead of session cookies
✔ CSRF Protection – Prevent unauthorized requests
✔ Secure Cookie Flags – Ensure cookies are transmitted safely
2. Storing Sessions Securely
A. Using Secure Cookies Instead of localStorage
Avoid: Storing session tokens in localStorage
(vulnerable to XSS attacks).
Use: HTTP-only secure cookies, which JavaScript cannot access.
Example: Setting Secure Cookies in Backend (Node.js + Express)
app.post('/api/login', (req, res) => {
const token = generateJWT(req.user);
res.cookie('sessionToken', token, {
httpOnly: true, // Prevents XSS attacks
secure: true, // Only sent over HTTPS
sameSite: 'Strict' // Prevents CSRF attacks
});
res.send({ success: true });
});
Why?
- httpOnly – JavaScript cannot access the cookie
- secure – Only transmitted over HTTPS
- sameSite – Prevents CSRF
3. Implementing Session Timeout in AngularJS
A. Auto-Logout on Inactivity
Example: Logout After 15 Minutes of Inactivity
app.run(['$rootScope', '$timeout', 'AuthService', function($rootScope, $timeout, AuthService) {
var timeoutPromise;
function resetTimer() {
if (timeoutPromise) $timeout.cancel(timeoutPromise);
timeoutPromise = $timeout(AuthService.logout, 15 * 60 * 1000); // 15 minutes
}
$rootScope.$on('$routeChangeStart', resetTimer);
document.addEventListener('mousemove', resetTimer);
document.addEventListener('keydown', resetTimer);
}]);
How It Works:
✔ If the user is inactive for 15 minutes, they are automatically logged out.
✔ Timer resets whenever user interacts with the app.
4. Using JWT for Secure Session Management
Instead of traditional sessions, use JSON Web Tokens (JWTs) for authentication.
Example: Generating a JWT on Login
app.service('AuthService', ['$http', '$window', function($http, $window) {
this.login = function(credentials) {
return $http.post('/api/login', credentials).then(function(response) {
$window.sessionStorage.setItem('token', response.data.token);
});
};
this.getToken = function() {
return $window.sessionStorage.getItem('token');
};
this.logout = function() {
$window.sessionStorage.removeItem('token');
};
}]);
Why JWT?
✔ Stateless – No need to store session on the server
✔ Signed – Can verify token integrity
✔ Short-Lived Tokens – Reduces risk
5. Protecting Routes Based on Session
Example: Preventing Access to Unauthorized Users
app.run(['$rootScope', 'AuthService', '$location', function($rootScope, AuthService, $location) {
$rootScope.$on('$routeChangeStart', function(event, next) {
if (next.requiresAuth && !AuthService.getToken()) {
event.preventDefault();
$location.path('/login');
}
});
}]);
How It Works:
✔ If a route requires authentication, but no token exists, redirect to login.
6. Preventing Cross-Site Request Forgery (CSRF)
CSRF Attacks happen when an attacker tricks a user into performing an unwanted action.
✔ Use CSRF tokens for extra security.
Example: Adding CSRF Token to Requests
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'XSRF-TOKEN';
$httpProvider.defaults.xsrfHeaderName = 'X-XSRF-TOKEN';
}]);
How It Works?
✔ CSRF token is stored in a cookie (XSRF-TOKEN
).
✔ Every API request includes the token in headers.
7. Encrypting Session Data Before Storing
Never store raw session data. Always encrypt it before saving to cookies or localStorage.
Example: Encrypting Data with CryptoJS
app.service('SecureStorageService', function() {
var secretKey = 'mySecretKey';
this.encrypt = function(data) {
return CryptoJS.AES.encrypt(JSON.stringify(data), secretKey).toString();
};
this.decrypt = function(ciphertext) {
var bytes = CryptoJS.AES.decrypt(ciphertext, secretKey);
return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
};
});
Example: Storing Secure Session Data
var encryptedData = SecureStorageService.encrypt({ userId: 123, role: 'Admin' });
localStorage.setItem('secureSession', encryptedData);
How It Works?
✔ AES Encryption protects data from theft.
✔ Even if an attacker accesses localStorage, data is useless without the key.
8. Implementing Secure Logout
Ensure sessions are fully cleared when a user logs out.
Example: Secure Logout Implementation
app.service('AuthService', ['$http', '$window', function($http, $window) {
this.logout = function() {
$window.sessionStorage.removeItem('token');
document.cookie = "sessionToken=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
};
}]);
How It Works?
✔ Deletes JWT from sessionStorage.
✔ Clears session cookies immediately.