Lecture 20: Security and Permission Management

Master Skill security and permission management, protect user data security, prevent common security risks.

1. Security Risk Analysis

1.1 Common Security Risks

Risk TypeDescriptionHarm
Data breachUser sensitive information accessed without authorizationPrivacy leakage, property loss
Injection attackMalicious code executed through inputSystem compromised, data destroyed
Privilege escalationUser accesses resources beyond permissionsData tampered, deleted
Session hijackingAttacker steals user sessionImpersonate user operations
API abuseInterface maliciously calledResource exhaustion, service interruption

1.2 Security Principles

1
2
3
4
5
6
7
8
9
10
11
Security Design Principles
├── Principle of Least Privilege
│ └── Only grant necessary permissions
├── Defense in Depth
│ └── Multi-layer security protection
├── Fail-Safe Defaults
│ └── Deny by default on error
├── Complete Mediation
│ └── Verify permissions on every access
└── Open Design
└── Don't rely on security through obscurity

2. Identity Authentication

2.1 Authentication Methods

from abc import ABC, abstractmethod
from typing import Optional
import hashlib
import secrets
import time

class Authenticator(ABC):
    """Authenticator base class"""

    @abstractmethod
    def authenticate(self, credentials: dict) -> Optional[str]:
        """Authenticate, return user ID or None"""
        pass

    @abstractmethod
    def verify_token(self, token: str) -> Optional[str]:
        """Verify token, return user ID or None"""
        pass

class APIKeyAuthenticator(Authenticator):
    """API Key authentication"""

    def __init__(self, storage):
        self.storage = storage

    def generate_api_key(self, user_id: str) -> str:
        """Generate API Key"""
        api_key = secrets.token_urlsafe(32)
        hashed_key = hashlib.sha256(api_key.encode()).hexdigest()

        # Store hash value
        self.storage.save(f"apikey:{hashed_key}", {
            'user_id': user_id,
            'created_at': time.time(),
            'last_used': time.time()


## 🎓 AI 编程实战课程

想系统学习 AI 编程?程序员晚枫的 **AI 编程实战课** 帮你从零上手!

- 👉 **课程报名**:[点击这里报名,前3讲免费试听](https://r7up9.xetslk.com/s/1uP5YW)
- 👉 **免费试看**:[B站免费试看前3讲,先看看适不适合自己](https://www.bilibili.com/cheese/play/ss982042944)