Preventing IDOR and Broken Access Control in Go net/http
A practical security engineering guide to preventing IDOR and broken access control in Go web applications using context scoping, compound SQL lookups, and Casbin.

Insecure Direct Object References (IDOR), categorized under Broken Access Control in the OWASP Top 10, frequently compromise Go web backends. Go’s standard library net/http package provides minimalist primitives: it routes requests and reads query parameters, but delegates all authorization, session management, and access control entirely to the developer.
In Go microservices, developers often establish authentication middleware that parses a JWT and validates that the caller is logged in. However, when the handler extracts a resource identifier from the URL path (e.g. using r.PathValue("id") in Go 1.22+ or chi.URLParam / mux.Vars) and passes it directly to a database repository without verifying ownership, an attacker can access, modify, or delete any user's records.
Before constructing defensive Go middleware, make sure your backend foundations are sound by checking our guides on database indexing strategies for high-performance SQL queries and rate limiting algorithms with Redis.
Understanding the Vulnerability Pattern in Go Handlers
A classic vulnerable Go HTTP handler illustrates the flaw:
// VULNERABLE HANDLER IMPLEMENTATION
func GetDocumentHandler(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Assume AuthMiddleware already validated that the user is logged in
docID := r.PathValue("id") // Go 1.22 standard router
// VULNERABILITY: Fetching document purely by primary key ID!
// Alice can supply Bob's document ID and view Bob's private confidential records.
var doc Document
query := `SELECT id, user_id, title, content FROM documents WHERE id = $1`
err := db.QueryRowContext(r.Context(), query, docID).Scan(&doc.ID, &doc.UserID, &doc.Title, &doc.Content)
if err == sql.ErrNoRows {
http.Error(w, "Document not found", http.StatusNotFound)
return
} else if err != nil {
http.Error(w, "Database error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(doc)
}
}
In this implementation, the database query executes successfully as long as docID exists in the documents table, completely ignoring whether doc.UserID matches the identity of the authenticated requestor.
| Security Dimension | Vulnerable Go Pattern | Hardened Defensive Go Pattern |
|---|---|---|
| Identity Flow | Storing claims in untyped global maps | Context-scoped values using unexported custom type keys |
| SQL Query Design | WHERE id = $1 |
Compound ownership filter: WHERE id = $1 AND user_id = $2 |
| Authorization Layer | Ad-hoc if doc.UserID != user.ID in handlers |
Reusable middleware or Casbin policy engine enforcement |
| Data Exposure | Sequential auto-increment integer IDs (/docs/42) |
Cryptographically secure UUIDv4 or KSUID (/docs/0ujtsY...) |
| Status Codes | Returning 403 Forbidden on access denial |
Returning 404 Not Found to prevent resource ID enumeration |
Technical Control 1: Type-Safe Context Propagation
In Go, passing authenticated user credentials across the HTTP middleware chain must be implemented using context.Context with an unexported type to prevent package key collisions:
package auth
import (
"context"
"net/http"
)
// Unexported context key prevents external package collisions
type contextKey struct{}
var userContextKey = contextKey{}
type UserClaims struct {
UserID int64
TenantID int64
Role string
}
// SetUserContext stores validated claims into the request context
func SetUserContext(r *http.Request, claims *UserClaims) *http.Request {
ctx := context.WithValue(r.Context(), userContextKey, claims)
return r.WithContext(ctx)
}
// GetUserFromContext retrieves authenticated claims with type safety
func GetUserFromContext(ctx context.Context) (*UserClaims, bool) {
claims, ok := ctx.Value(userContextKey).(*UserClaims)
return claims, ok && claims != nil
}
Now, any downstream handler can safely retrieve the authenticated caller's identity without string parsing or reflection overhead.
Technical Control 2: Compound Query Enforcement at the Storage Layer
The most robust architectural defense against IDOR in Go is enforcing compound lookups inside repository methods. A repository method should never accept only an entity ID if the entity belongs to a user or tenant:
type DocumentRepository struct {
db *sql.DB
}
// FindByIDAndUser guarantees that a user cannot query another user's document
func (repo *DocumentRepository) FindByIDAndUser(ctx context.Context, id int64, userID int64) (*Document, error) {
query := `
SELECT id, user_id, title, content, updated_at
FROM documents
WHERE id = $1 AND user_id = $2
`
var doc Document
err := repo.db.QueryRowContext(ctx, query, id, userID).Scan(
&doc.ID,
&doc.UserID,
&doc.Title,
&doc.Content,
&doc.UpdatedAt,
)
if err != nil {
return nil, err // Returns sql.ErrNoRows if not found or not owned
}
return &doc, nil
}
Now, update the HTTP handler to use this repository method:
func (h *DocumentHandler) GetDocument(w http.ResponseWriter, r *http.Request) {
user, ok := auth.GetUserFromContext(r.Context())
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
docID, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.Error(w, "Invalid document ID", http.StatusBadRequest)
return
}
doc, err := h.repo.FindByIDAndUser(r.Context(), docID, user.UserID)
if errors.Is(err, sql.ErrNoRows) {
// Return 404 to hide document existence from unauthorized callers
http.Error(w, "Document not found", http.StatusNotFound)
return
} else if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(doc)
}
Technical Control 3: Fine-Grained Authorization with Casbin
When authorization rules expand beyond simple single-user ownership (e.g. role hierarchies, team permissions, organization boundaries), hardcoding SQL queries becomes unmaintainable.
Casbin is a battle-tested authorization library for Go supporting RBAC and ABAC models:
Step 1: Define the ABAC Model (model.conf)
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = r.sub.Role == "admin" || (r.sub.TenantID == r.obj.TenantID && r.act == "read")
Step 2: Enforce the Policy in Go Code
import "github.com/casbin/casbin/v2"
func CheckPermission(e *casbin.Enforcer, user *UserClaims, doc *Document, action string) bool {
allowed, err := e.Enforce(user, doc, action)
if err != nil {
return false
}
return allowed
}
This decouples policy definition from handler code, ensuring business rule changes can be audited and modified centrally.
Technical Control 4: Automated Testing with httptest
Writing automated security tests in Go ensures that authorization bypasses cannot slip into production builds. Using the standard library net/http/httptest package:
func TestGetDocument_CrossUserAccess_ReturnsNotFound(t *testing.T) {
db := setupTestDatabase(t)
defer db.Close()
// Seed test data: Document 100 owned by User 20
_, err := db.Exec("INSERT INTO documents (id, user_id, title) VALUES (100, 20, 'Confidential')")
require.NoError(t, err)
handler := NewDocumentHandler(NewDocumentRepository(db))
// Create request pretending to be authenticated as User 99 (Attacker)
req := httptest.NewRequest(http.MethodGet, "/documents/100", nil)
req.SetPathValue("id", "100")
req = auth.SetUserContext(req, &auth.UserClaims{UserID: 99})
rr := httptest.NewRecorder()
handler.GetDocument(rr, req)
// Assert that User 99 cannot access User 20's document
if rr.Code != http.StatusNotFound {
t.Fatalf("Expected 404 Not Found, got %d. IDOR vulnerability detected!", rr.Code)
}
}
Security Review Checklist for Go Endpoints
Before approving PRs for Go web services:
- Are all path parameters (
r.PathValue) validated and cast to strong types? - Does the SQL query include
AND user_id = ?orAND organization_id = ?? - Is user identity extracted strictly from server-side context (
r.Context()), never from client-provided headers or JSON bodies? - Do endpoints return
404 Not Foundon ownership mismatches to prevent integer enumeration? - Are state-changing operations (
PUT,DELETE) verified with identical ownership constraints?
Official Documentation and Further Reading
- Go standard library: net/http Routing Enhancements
- Casbin: An authorization library that supports access control models in Golang
- OWASP Cheat Sheet: Authorization Cheat Sheet
Application Security Defense Matrix: Insecure Direct Object References (IDOR), Go net/http Guide.


