Security Best Practices

Comprehensive security guidelines for implementing and maintaining a secure OAuth42 integration.

Core Security Principles

Defense in Depth

Implement multiple layers of security controls. If one layer fails, others remain to protect your application and user data.

Least Privilege

Grant the minimum permissions necessary for each component, user, or service to perform its intended function.

Zero Trust

Never trust, always verify. Validate every request, even from internal services. Treat all networks as potentially hostile.

Security by Default

Secure configurations should be the default. Require explicit action to reduce security, not to increase it.

OAuth 2.0 & OIDC Security

Always Use PKCE

Proof Key for Code Exchange (PKCE) is required for all authorization code flows. This prevents authorization code interception attacks.

✓ Correct

// Generate PKCE parameters
const codeVerifier = generateRandomString(128);
const codeChallenge = base64url(sha256(codeVerifier));

// Include in authorization request
const authUrl = `${authEndpoint}?client_id=${clientId}&redirect_uri=${redirectUri}&response_type=code&code_challenge=${codeChallenge}&code_challenge_method=S256`;

Validate Redirect URIs

Only allow exact match redirect URIs. Never use wildcards or pattern matching.

✗ Insecure

// ❌ Never do this
redirect_uri: "https://*.example.com/callback"
redirect_uri: "https://example.com/*"

✓ Secure

// ✅ Use exact URLs
redirect_uri: "https://app.example.com/oauth/callback"
redirect_uri: "https://example.com/auth/callback"

Use State Parameter

Always include a random state parameter to prevent CSRF attacks. Verify it matches on callback.

// Generate and store state
const state = generateRandomString(32);
sessionStorage.setItem('oauth_state', state);

// Include in authorization request
const authUrl = `${authEndpoint}?...${state}`;

// Verify on callback
const returnedState = new URLSearchParams(location.search).get('state');
const storedState = sessionStorage.getItem('oauth_state');

if (returnedState !== storedState) {
  throw new Error('State mismatch - possible CSRF attack');
}

Validate ID Tokens

When using OpenID Connect, always validate ID tokens before trusting their claims.

  • Verify signature using JWKS from discovery endpoint
  • Check issuer (iss) matches expected value
  • Verify audience (aud) matches your client ID
  • Confirm token hasn't expired (exp)
  • Validate issued at time (iat) is reasonable
  • Check nonce matches if provided in request

Token Security

Secure Token Storage

Storage method impacts security significantly. Choose appropriate storage for your application type.

✓ Recommended: HTTP-Only Cookies

Best for web applications:

Set-Cookie: access_token=...; HttpOnly; Secure; SameSite=Strict; Path=/
  • • Not accessible via JavaScript (XSS protection)
  • • Secure flag requires HTTPS
  • • SameSite prevents CSRF

⚠ Acceptable: sessionStorage

For single-tab session:

  • • Cleared when tab closes
  • • Not shared across tabs
  • • Vulnerable to XSS
  • • Use only if HTTP-only cookies unavailable

✗ Not Recommended: localStorage

High XSS risk:

  • • Persists across sessions
  • • Accessible from any script
  • • Vulnerable to XSS attacks
  • • Avoid for sensitive tokens

Token Expiration

Use short-lived access tokens with longer-lived refresh tokens:

  • Access tokens: 15-60 minutes
  • Refresh tokens: Days to months (with rotation)
  • ID tokens: Match access token lifetime

Token Rotation

Implement refresh token rotation to limit exposure:

// When refreshing, OAuth42 returns new tokens
POST /oauth/token
{
  "grant_type": "refresh_token",
  "refresh_token": "old_refresh_token",
  "client_id": "your_client_id"
}

Response:
{
  "access_token": "new_access_token",
  "refresh_token": "new_refresh_token",  // ← New token
  "expires_in": 3600
}

// Old refresh token is now invalid

API Security

Always Use HTTPS

Never transmit credentials or tokens over HTTP. Use TLS 1.2 or higher.

  • • Use valid SSL certificates (not self-signed in production)
  • • Enable HSTS (HTTP Strict Transport Security)
  • • Implement certificate pinning for mobile apps
  • • Redirect HTTP to HTTPS automatically

Rate Limiting

Protect APIs from abuse with rate limiting:

# Rate limit headers in responses
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640000000

# Recommended limits:
# - Authentication endpoints: 5 req/min per IP
# - Token refresh: 10 req/min per token
# - General API: 1000 req/hour per user

Input Validation

Validate and sanitize all input to prevent injection attacks:

  • • Validate data types, formats, and ranges
  • • Sanitize user input before database queries
  • • Use parameterized queries (never string concatenation)
  • • Implement schema validation for API requests
  • • Reject requests with unexpected fields

CORS Configuration

Configure Cross-Origin Resource Sharing (CORS) properly:

// ❌ Never use wildcards with credentials
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

// ✅ Specify exact origins
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Max-Age: 3600

Client Application Security

Secret Management

Handle client secrets with extreme care:

✗ Never Do This

  • • Commit secrets to version control
  • • Include secrets in frontend code
  • • Log secrets in application logs
  • • Share secrets via email or chat
  • • Hardcode secrets in source code

✓ Best Practices

  • • Use environment variables
  • • Store in secure secret management (Vault, AWS Secrets Manager)
  • • Rotate secrets regularly
  • • Use different secrets per environment
  • • Limit secret access to necessary services

Public vs Confidential Clients

Understand the difference and configure accordingly:

Public Clients

Cannot securely store secrets:

  • • Single Page Apps (SPAs)
  • • Mobile applications
  • • Desktop applications

Must use: PKCE, no client secret

Confidential Clients

Can securely store secrets:

  • • Server-side web apps
  • • Backend services
  • • Secure servers

Should use: PKCE + client secret

Content Security Policy (CSP)

Implement CSP headers to prevent XSS attacks:

Content-Security-Policy:
  default-src 'self';
  script-src 'self' 'strict-dynamic';
  style-src 'self' 'unsafe-inline';
  img-src 'self' data: https:;
  connect-src 'self' https://auth.oauth42.com;
  frame-ancestors 'none';
  base-uri 'self';
  form-action 'self';

Monitoring & Incident Response

Security Monitoring

Monitor and alert on security-relevant events:

  • • Multiple failed login attempts from same IP
  • • Login from new device or location
  • • Unusual API usage patterns
  • • Token refresh from unexpected location
  • • Account permission changes
  • • MFA disabled or modified
  • • Multiple 4xx or 5xx errors

Audit Logging

Maintain comprehensive audit logs:

{
  "timestamp": "2025-01-15T10:30:00Z",
  "event": "user.login.success",
  "user_id": "user_12345",
  "ip_address": "203.0.113.0",
  "user_agent": "Mozilla/5.0...",
  "location": "San Francisco, CA",
  "mfa_used": true,
  "device_id": "device_abc123"
}

Store logs securely and retain for compliance requirements (typically 90+ days).

Incident Response Plan

Prepare for security incidents:

  1. Detect: Automated monitoring and alerting
  2. Respond: Immediate containment actions
  3. Investigate: Root cause analysis
  4. Remediate: Fix vulnerabilities
  5. Communicate: Notify affected users
  6. Learn: Post-mortem and improvements

Compliance & Regulations

GDPR Compliance

For European users, implement GDPR requirements:

  • • Obtain explicit consent for data processing
  • • Allow users to access their data (data portability)
  • • Implement "right to be forgotten" (account deletion)
  • • Document data processing activities
  • • Report breaches within 72 hours
  • • Encrypt personal data at rest and in transit

SOC 2 Considerations

For B2B SaaS applications:

  • • Implement access controls and authorization
  • • Maintain audit logs for all security events
  • • Regular security training for team
  • • Vulnerability scanning and penetration testing
  • • Incident response procedures
  • • Vendor security assessments

Industry Standards

Follow relevant security standards:

  • OAuth 2.0 Security BCP: RFC 6749, RFC 6819
  • OIDC Core: OpenID Connect specification
  • OWASP Top 10: Common web vulnerabilities
  • NIST Guidelines: Password and authentication

Security Checklist

Use this checklist to verify your OAuth42 integration security:

PKCE implemented for all authorization code flows
Redirect URIs use exact matching (no wildcards)
State parameter used and validated
All communication uses HTTPS/TLS 1.2+
Tokens stored securely (HTTP-only cookies preferred)
Short-lived access tokens (15-60 minutes)
Refresh token rotation enabled
ID tokens validated (signature, issuer, audience, expiration)
Client secrets stored securely (not in code/VCS)
Rate limiting implemented on auth endpoints
Input validation on all API endpoints
CORS configured properly (no wildcard with credentials)
Content Security Policy (CSP) headers set
MFA enabled for sensitive operations
Security monitoring and alerting configured
Audit logging for security events
Incident response plan documented
Regular security assessments scheduled

Next Steps