logging auth events without leaking sensitive data
auth event logging, what to log, PII in logs, token logging danger, structured logging, log levels, SIEM integration, audit trail requirements
Logging Auth Events Without Leaking Sensitive Data
Auth logs are your intrusion detection system. Log the right things and you catch attacks. Log the wrong things and you create new vulnerabilities.
Always log: login success/failure, logout, password change, role change, rate limit triggers, token refresh, OAuth link/unlink. Include: timestamp, event type, user ID (not username/email in logs), IP address, user agent, success/failure flag.
Never log: passwords (obvious), full JWT tokens (replayable), session IDs (hijackable), full OAuth access tokens, credit card numbers, any PII unless legally required with encryption at rest.
const logger = require('pino')(); // structured JSON logger
function logAuthEvent(event, req, extra = {}) {
logger.info({
event,
userId: req.user?.id ?? null,
ip: req.ip,
userAgent: req.headers['user-agent'],
timestamp: new Date().toISOString(),
...extra
});
}
// Usage
logAuthEvent('login.success', req, { method: 'password' });
logAuthEvent('login.failure', req, { reason: 'invalid_password' });
logAuthEvent('token.refresh', req);
logAuthEvent('role.changed', req, { targetUserId: params.id, newRole: body.role });Use structured logging (JSON output). Unstructured text logs cannot be queried. Ship auth logs to a separate, append-only log store โ attackers who compromise your app should not be able to erase their tracks.
