Session Management
Session Management
Secure session management prevents unauthorized access and session hijacking.
// Android - Secure session management
class SessionManager(private val context: Context) {
companion object {
private const val SESSION_TIMEOUT = 30 * 60 * 1000L // 30 minutes
private const val REFRESH_THRESHOLD = 5 * 60 * 1000L // 5 minutes
private const val MAX_SESSION_DURATION = 24 * 60 * 60 * 1000L // 24 hours
}
private val secureStorage = SecurePreferencesManager(context)
private val sessionLock = Any()
@Volatile
private var currentSession: Session? = null
// Create new session after authentication
fun createSession(
userId: String,
authMethod: AuthMethod,
deviceInfo: DeviceInfo
): Session {
synchronized(sessionLock) {
// Invalidate any existing session
currentSession?.let { invalidateSession(it) }
val session = Session(
id = generateSessionId(),
userId = userId,
createdAt = System.currentTimeMillis(),
lastActivityAt = System.currentTimeMillis(),
expiresAt = System.currentTimeMillis() + SESSION_TIMEOUT,
authMethod = authMethod,
deviceInfo = deviceInfo,
isActive = true
)
// Store session securely
storeSession(session)
currentSession = session
// Schedule session timeout
scheduleSessionTimeout(session)
// Log session creation for audit
logSessionEvent(SessionEvent.CREATED, session)
return session
}
}
// Validate and refresh session
fun validateSession(): SessionValidationResult {
synchronized(sessionLock) {
val session = currentSession ?: loadStoredSession()
if (session == null) {
return SessionValidationResult.NO_SESSION
}
// Check if session is expired
if (System.currentTimeMillis() > session.expiresAt) {
invalidateSession(session)
return SessionValidationResult.EXPIRED
}
// Check if session has exceeded maximum duration
if (System.currentTimeMillis() - session.createdAt > MAX_SESSION_DURATION) {
invalidateSession(session)
return SessionValidationResult.MAX_DURATION_EXCEEDED
}
// Check if device info matches
if (!verifyDeviceInfo(session.deviceInfo)) {
invalidateSession(session)
return SessionValidationResult.DEVICE_MISMATCH
}
// Refresh session if needed
if (shouldRefreshSession(session)) {
val refreshedSession = refreshSession(session)
currentSession = refreshedSession
return SessionValidationResult.VALID_REFRESHED
}
// Update last activity
updateLastActivity(session)
return SessionValidationResult.VALID
}
}
private fun shouldRefreshSession(session: Session): Boolean {
val timeUntilExpiry = session.expiresAt - System.currentTimeMillis()
return timeUntilExpiry < REFRESH_THRESHOLD
}
private fun refreshSession(session: Session): Session {
val refreshedSession = session.copy(
lastActivityAt = System.currentTimeMillis(),
expiresAt = System.currentTimeMillis() + SESSION_TIMEOUT
)
storeSession(refreshedSession)
scheduleSessionTimeout(refreshedSession)
logSessionEvent(SessionEvent.REFRESHED, refreshedSession)
return refreshedSession
}
private fun verifyDeviceInfo(storedInfo: DeviceInfo): Boolean {
val currentInfo = getCurrentDeviceInfo()
// Allow minor OS updates but detect major changes
return storedInfo.deviceId == currentInfo.deviceId &&
storedInfo.manufacturer == currentInfo.manufacturer &&
storedInfo.model == currentInfo.model &&
storedInfo.osMajorVersion == currentInfo.osMajorVersion
}
private fun generateSessionId(): String {
val random = SecureRandom()
val bytes = ByteArray(32)
random.nextBytes(bytes)
return Base64.encodeToString(bytes, Base64.URL_SAFE or Base64.NO_WRAP)
}
data class Session(
val id: String,
val userId: String,
val createdAt: Long,
val lastActivityAt: Long,
val expiresAt: Long,
val authMethod: AuthMethod,
val deviceInfo: DeviceInfo,
val isActive: Boolean
)
enum class SessionValidationResult {
VALID,
VALID_REFRESHED,
NO_SESSION,
EXPIRED,
MAX_DURATION_EXCEEDED,
DEVICE_MISMATCH
}
}
Authentication and authorization are fundamental to mobile application security. By implementing modern authentication methods like biometrics and MFA, following OAuth 2.0 best practices, and maintaining robust session management, developers can create secure yet user-friendly authentication systems. Remember that security is an ongoing process—regularly review and update your authentication mechanisms to address emerging threats and leverage new platform capabilities. The next chapter explores mobile app security testing to validate these implementations.## Mobile App Security Testing
Security testing is a critical phase in the mobile application development lifecycle that ensures your security implementations work as intended and identifies vulnerabilities before attackers can exploit them. This chapter provides a comprehensive guide to mobile app security testing, covering both automated and manual testing techniques, platform-specific considerations, and integration into the development workflow.