Secure Authentication Practices
Password hashing, session management, 2FA, OAuth best practices.
securityauthbackend
# Secure Authentication Practices
## Password hashing
```ts
import bcrypt from 'bcrypt'
// Hash (cost factor 12, ~250ms)
const hash = await bcrypt.hash(password, 12)
// Verify
const valid = await bcrypt.compare(inputPassword, storedHash)
```
Never: MD5, SHA-256 (too fast), plain text. Use: bcrypt, scrypt, argon2.
## Session management
```ts
// Generate session ID
import crypto from 'node:crypto'
const sessionId = crypto.randomBytes(32).toString('hex')
// Cookie settings
res.cookie('sid', sessionId, {
httpOnly: true, // no JS access
secure: true, // HTTPS only
sameSite: 'lax', // CSRF protection
maxAge: 86400000, // 24h
path: '/',
})
// Store session server-side (Redis)
await redis.setex(`sess:${sessionId}`, 86400, JSON.stringify({ userId, role }))
```
## JWT best practices
```ts
import jwt from 'jsonwebtoken'
// Sign (short-lived access token)
const accessToken = jwt.sign(
{ sub: userId, role },
process.env.JWT_SECRET,
{ expiresIn: '15m', algorithm: 'HS256' }
)
// Refresh token: long-lived, stored in httpOnly cookie, single-use.
// Rotate refresh token on each use. Store in DB to allow revocation.
```
## Two-Factor Authentication (2FA)
```ts
import { authenticator } from 'otplib'
// Setup: generate secret, show QR code
const secret = authenticator.generateSecret()
const otpUri = authenticator.keyuri(email, 'MyApp', secret)
// -> show as QR code with 'qrcode' package
// Verify on login
const isValid = authenticator.verify({ token: userOTP, secret: storedSecret })
```
## OAuth 2.0 security
- Always use Authorization Code flow (not Implicit).
- Use PKCE for public clients (SPAs, mobile).
- Validate `state` parameter to prevent CSRF.
- Store tokens securely (httpOnly cookies, not localStorage).
## Checklist
- [ ] Passwords hashed with bcrypt/scrypt/argon2 (cost ≥ 12).
- [ ] Sessions stored server-side, cookie is httpOnly + secure.
- [ ] Enforce rate limiting on login (5 attempts / 15 min).
- [ ] Account lockout or CAPTCHA after repeated failures.
- [ ] Password strength requirements (min 8 chars, check breached list).
- [ ] Offer 2FA (TOTP preferred over SMS).
API: /api/skills/secure-authentication