Principles and Implementation of Authentication & Authorization

Principles and Implementation of Authentication & Authorization

1. Concepts and Differences

  • Authentication: Verifies a user's identity, addressing the question "Who are you?". For example, a user logs into a system by entering a username and password.
  • Authorization: Verifies whether a user has permission to perform an operation, addressing the question "What can you do?". For example, an administrator can delete articles, while a regular user can only browse.
  • Relationship: Authentication is a prerequisite for authorization. The system must first confirm the user's identity, then control access based on their roles or permissions.

2. Common Authentication Methods and Principles

(1) Session-Cookie Authentication

  • Process:
    1. The user submits credentials (e.g., password). After successful verification, the server creates a session (Session) to store data such as the user ID.
    2. The server returns a Cookie (containing the Session ID) to the browser, which automatically includes this Cookie in subsequent requests.
    3. The server retrieves the session data via the Session ID to verify the user's identity.
  • Security: The Session ID must be randomly generated and have an expiration time to prevent impersonation if stolen.

(2) Token Authentication (e.g., JWT)

  • Process:
    1. After the user logs in, the server generates a Token (containing user information, a signature, and an expiration time) and returns it to the client.
    2. The client includes the Token in subsequent requests via the Header (e.g., Authorization: Bearer <token>).
    3. The server verifies the Token's signature and validity period, with no need to store session state.
  • Advantages: Stateless, suitable for distributed systems; however, once issued, a Token cannot be forcibly invalidated before it expires.

3. Core Authorization Models

(1) Role-Based Access Control (RBAC)

  • Principle:
    • Define roles (e.g., Admin, Editor, Guest) and assign permissions to them (e.g., "delete article," "modify settings").
    • Users indirectly gain permissions by being associated with roles.
  • Example:
    -- Database table structure  
    Users: id, name, role_id  
    Roles: id, name  
    Permissions: id, action  -- e.g., "article:delete"  
    Role_Permissions: role_id, permission_id  
    
  • Check Logic: Query whether the user's associated role has the permission for a specific operation.

(2) Attribute-Based Access Control (ABAC)

  • Principle: Define policies based on dynamic attributes (e.g., user department, resource type, time).
  • Example:
    Policy: Allow "employees from Department A" to access "documents from Department A" during "working hours".  
    
  • Advantages: More flexible, but policy management is complex.

4. Implementation Example: RBAC Middleware Design

Taking a web framework's middleware as an example to check user permissions:

def permission_required(permission):  
    def decorator(view_func):  
        @wraps(view_func)  
        def wrapped_view(request, *args, **kwargs):  
            # 1. Retrieve the user from the request (already attached via authentication middleware)  
            user = request.user  
            # 2. Check if the user possesses the required permission  
            if not user.has_permission(permission):  
                return HttpResponse("Forbidden", status=403)  
            return view_func(request, *args, **kwargs)  
        return wrapped_view  
    return decorator  

# Usage example  
@permission_required("article:delete")  
def delete_article(request):  
    # Logic for deleting an article  
    pass  

5. Security Considerations

  • Authentication Security:
    • Passwords must be stored with salted hashes (e.g., bcrypt).
    • Use HTTPS to prevent credential leakage.
    • Implement login attempt limits to prevent brute-force attacks.
  • Authorization Security:
    • Default to denying all requests, only explicitly permitting necessary permissions.
    • Server-side permission validation is mandatory; client-side checks are only for user experience optimization.

6. Extensions: OAuth 2.0 and OpenID Connect

  • OAuth 2.0: Authorizes third-party applications to access user resources (e.g., using WeChat to log into a third-party website) but does not involve identity authentication.
  • OpenID Connect: Adds an identity authentication layer on top of OAuth 2.0, providing user information endpoints.

By following the steps above, a system can securely manage user identities and permissions, adapting to business scenarios of varying scales.