Secure Authentication and Authorization Standards

Secure Authentication and Authorization Standards

Authentication and authorization standards ensure that only legitimate users can access the system and that they can only perform actions appropriate to their role. These standards cover password policies, session management, API authentication, and access control patterns.

# Python Authentication Standards

import secrets
import hashlib
from datetime import datetime, timedelta
from typing import Dict, List, Optional
import bcrypt
import pyotp
from functools import wraps

class AuthenticationStandards:
    """Standard authentication patterns and requirements"""
    
    # Password policy constants
    MIN_PASSWORD_LENGTH = 12
    MAX_PASSWORD_LENGTH = 128
    PASSWORD_HISTORY_SIZE = 5
    PASSWORD_EXPIRY_DAYS = 90
    MAX_LOGIN_ATTEMPTS = 5
    LOCKOUT_DURATION_MINUTES = 30
    
    # Session configuration
    SESSION_TIMEOUT_MINUTES = 30
    ABSOLUTE_SESSION_TIMEOUT_HOURS = 12
    SESSION_ID_LENGTH = 32
    
    @staticmethod
    def validate_password_strength(password: str) -> Dict[str, bool]:
        """Validate password meets security requirements"""
        checks = {
            'min_length': len(password) >= AuthenticationStandards.MIN_PASSWORD_LENGTH,
            'max_length': len(password) <= AuthenticationStandards.MAX_PASSWORD_LENGTH,
            'has_uppercase': bool(re.search(r'[A-Z]', password)),
            'has_lowercase': bool(re.search(r'[a-z]', password)),
            'has_digit': bool(re.search(r'\d', password)),
            'has_special': bool(re.search(r'[!@#$%^&*(),.?":{}|<>]', password)),
            'no_common_patterns': not any(pattern in password.lower() for pattern in [
                'password', '12345', 'qwerty', 'admin', 'letmein'
            ])
        }
        
        checks['is_valid'] = all(checks.values())
        return checks
    
    @staticmethod
    def hash_password(password: str) -> str:
        """Hash password using bcrypt with appropriate cost factor"""
        # Use cost factor 12 (can be adjusted based on performance requirements)
        return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(12)).decode('utf-8')
    
    @staticmethod
    def generate_secure_token(length: int = 32) -> str:
        """Generate cryptographically secure random tokens"""
        return secrets.token_urlsafe(length)
    
    @staticmethod
    def generate_session_id() -> str:
        """Generate secure session identifier"""
        # Combine multiple sources of randomness
        random_bytes = secrets.token_bytes(32)
        timestamp = str(datetime.utcnow().timestamp()).encode()
        
        # Hash the combination
        session_data = random_bytes + timestamp
        session_id = hashlib.sha256(session_data).hexdigest()
        
        return session_id
    
    @classmethod
    def create_secure_session(cls, user_id: int, ip_address: str, user_agent: str) -> Dict:
        """Create a secure session with all necessary attributes"""
        now = datetime.utcnow()
        
        return {
            'session_id': cls.generate_session_id(),
            'user_id': user_id,
            'created_at': now,
            'last_activity': now,
            'expires_at': now + timedelta(minutes=cls.SESSION_TIMEOUT_MINUTES),
            'absolute_timeout': now + timedelta(hours=cls.ABSOLUTE_SESSION_TIMEOUT_HOURS),
            'ip_address': ip_address,
            'user_agent': user_agent,
            'csrf_token': cls.generate_secure_token(16),
            'is_active': True
        }
    
    @staticmethod
    def setup_totp(user_id: str) -> Dict[str, str]:
        """Setup TOTP-based two-factor authentication"""
        # Generate a random secret
        secret = pyotp.random_base32()
        
        # Create provisioning URI for QR code
        totp = pyotp.TOTP(secret)
        provisioning_uri = totp.provisioning_uri(
            name=user_id,
            issuer_name='YourApp'
        )
        
        return {
            'secret': secret,
            'provisioning_uri': provisioning_uri
        }
    
    @staticmethod
    def verify_totp(secret: str, token: str) -> bool:
        """Verify TOTP token"""
        totp = pyotp.TOTP(secret)
        
        # Allow for time drift (1 period before/after)
        return totp.verify(token, valid_window=1)

class AuthorizationStandards:
    """Standard authorization patterns and RBAC implementation"""
    
    @staticmethod
    def check_permission(user_permissions: List[str], required_permission: str) -> bool:
        """Check if user has required permission"""
        # Implement hierarchical permission checking
        parts = required_permission.split('.')
        
        for i in range(len(parts), 0, -1):
            # Check for exact match or wildcard
            check_perm = '.'.join(parts[:i])
            if check_perm in user_permissions:
                return True
            
            # Check for wildcard permission
            wildcard_perm = '.'.join(parts[:i-1] + ['*'])
            if wildcard_perm in user_permissions:
                return True
        
        return False
    
    @staticmethod
    def require_permission(permission: str):
        """Decorator for checking permissions"""
        def decorator(f):
            @wraps(f)
            def decorated_function(*args, **kwargs):
                # Get current user from context (framework-specific)
                current_user = get_current_user()
                
                if not current_user:
                    raise UnauthorizedException("Authentication required")
                
                if not AuthorizationStandards.check_permission(
                    current_user.permissions, permission
                ):
                    raise ForbiddenException(
                        f"Permission '{permission}' required"
                    )
                
                return f(*args, **kwargs)
            
            return decorated_function
        return decorator
    
    @staticmethod
    def sanitize_rbac_check(role: str, resource: str, action: str) -> bool:
        """Secure RBAC check with input validation"""
        # Validate inputs
        if not all(isinstance(x, str) for x in [role, resource, action]):
            raise ValueError("Invalid input types for RBAC check")
        
        # Validate against allowed values
        allowed_roles = ['admin', 'user', 'guest', 'moderator']
        allowed_actions = ['read', 'write', 'delete', 'execute']
        
        if role not in allowed_roles:
            raise ValueError(f"Invalid role: {role}")
        
        if action not in allowed_actions:
            raise ValueError(f"Invalid action: {action}")
        
        # Validate resource format
        if not re.match(r'^[a-zA-Z0-9_/]+$', resource):
            raise ValueError(f"Invalid resource format: {resource}")
        
        # Perform RBAC check
        return perform_rbac_check(role, resource, action)

These secure coding standards provide a foundation for building robust and secure applications. By following these guidelines consistently, development teams can significantly reduce the risk of security vulnerabilities in their code. Regular reviews and updates of these standards ensure they remain effective against evolving threats.## OWASP Top 10 Python JavaScript

The OWASP Top 10 represents the most critical security risks to web applications, and understanding how these vulnerabilities manifest in Python and JavaScript is essential for developers. This chapter provides a detailed examination of each OWASP Top 10 risk, showing specific examples in both languages and demonstrating secure coding practices to mitigate these vulnerabilities. By understanding these risks in the context of the languages you use daily, you can build more secure applications from the ground up.