Authorization Basics for APIs — Complete Access Control Guide
In this tutorial, you will learn about Authorization Basics for APIs. We cover key concepts, practical examples, and best practices to help you master this topic.
Authorization determines what an authenticated user is allowed to do. While authentication answers "who are you?", authorization answers "what can you do?".
What You'll Learn
You'll learn role-based access control (RBAC), attribute-based access control (ABAC), and how to implement authorization in your APIs.
Why It Matters
Without proper authorization, any authenticated user can access any resource. This leads to privilege escalation, data leaks, and Compliance violations.
Real-World Use
A cloud storage API uses authorization to ensure User A can only read and write their own files, while admins can manage all users but cannot view file contents.
flowchart TD
A[Authenticated Request] --> B{Check Role}
B -->|Admin| C[Full Access]
B -->|Editor| D{Check Resource Owner}
B -->|Viewer| E[Read Only]
D -->|Own Resource| F[Read/Write]
D -->|Other's Resource| G[Read Only]
C --> H[Return Response]
F --> H
E --> H
G --> H
Teacher's Mindset
Authorization is like a building with different access levels. A regular employee can enter their office. Managers can access the executive floor. Only security has the server room key.
Implementing Authorization
from flask import Flask, request, jsonify
from functools import wraps
app = Flask(__name__)
ROLES = {
"admin": ["read", "write", "delete", "manage_users"],
"editor": ["read", "write"],
"viewer": ["read"]
}
def require_permission(permission):
def decorator(f):
@wraps(f)
def decorated(*args, **kwargs):
user_role = request.headers.get("X-User-Role")
if not user_role or permission not in ROLES.get(user_role, []):
return jsonify({"error": "Forbidden"}), 403
return f(*args, **kwargs)
return decorated
return decorator
@app.route("/api/posts", methods=["POST"])
@require_permission("write")
def create_post():
return jsonify({"message": "Post created"})
# Attribute-based access control
def check_access(user, resource, action):
if user["role"] == "admin":
return True
if resource["owner_id"] == user["id"]:
return True
if action == "read" and resource["visibility"] == "public":
return True
return False
users = [{"id": 1, "role": "editor"}]
resources = [{"id": 101, "owner_id": 2, "visibility": "private"}]
user = users[0]
resource = resources[0]
if check_access(user, resource, "read"):
print("Access granted")
else:
print("Access denied")
# Middleware-based authorization
class AuthorizationMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
user = request.user
path = request.path
method = request.method
if path.startswith("/api/admin") and user.role != "admin":
return JsonResponse({"error": "Forbidden"}, status=403)
return self.get_response(request)
Common Mistakes
| Mistake | Why It's Wrong | Fix |
|---|---|---|
| Checking auth but not authz | Authenticated users get full access | Check permissions for every operation |
| Hardcoding roles in code | Cannot change permissions without deploy | Store roles and permissions in database |
| Insecure direct object references | Users can access other users' data | Verify resource ownership on every request |
| Missing authorization on list endpoints | Users can enumerate all resources | Filter lists by user permissions |
| Relying solely on frontend authz | Attackers can call APIs directly | Enforce authorization server-side |
Practice Questions
- What is the difference between RBAC and ABAC?
- What is the principle of Least Privilege?
- How does insecure direct object reference work?
- Why must authorization be enforced server-side?
- What is privilege escalation?
Challenge
Implement RBAC with roles admin, manager, and user. Admin can delete anything, manager can edit their department's data, user can only read their own data.
FAQ
Mini Project
Build an API with three roles (admin, editor, viewer) and document-level permissions. Each document has an owner and visibility setting. Enforce access control at the endpoint level.
What's Next
Learn how JWT secures authentication tokens with signatures and claims.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro