Course contentsShow
← Security
Lesson 869 of 3,05218. Web Security - CSRF and Request ForgeryFree lesson

Origin and Referer Validation

Check Origin and Referer headers to verify requests originate from trusted sources.

Origin and Referer Validation

You'll learn: How to check Origin and Referer headers to confirm that requests come from legitimate sources you trust.

What Are Origin and Referer Headers?

When your browser sends a request, it automatically includes headers that tell the server where the request came from:

  • Origin: Shows the protocol, domain, and port of the page making the request (e.g., https://yourbank.com)
  • Referer: Shows the full URL of the page that initiated the request (e.g., https://yourbank.com/transfer-money)

Think of these like a return address on an envelope—they tell you who sent the package.

Using Them for CSRF Defense

As a CSRF defense layer, your server can check these headers to verify requests originate from your own domain:

# Server-side validation example
def is_request_legitimate(request):
    allowed_origins = ['https://yourbank.com']
    
    origin = request.headers.get('Origin')
    referer = request.headers.get('Referer')
    
    # Check Origin header (present in CORS/state-changing requests)
    if origin and origin not in allowed_origins:
        return False
    
    # Check Referer as fallback
    if referer and not referer.startswith('https://yourbank.com'):
        return False
    
    return True

Limitations to Know

This defense isn't foolproof:

  • Referer can be missing: Users/browsers may suppress it for privacy
  • Not all requests include Origin: Older browsers or certain request types
  • Header spoofing: In rare scenarios, headers might be manipulated

That's why Origin/Referer validation works best as a supplementary defense alongside Synchronizer Token Pattern, Double Submit Cookie, or SameSite Cookie Attribute.

Key Takeaway: Validating Origin and Referer headers adds a verification layer to confirm requests originate from your trusted domain, but should be combined with stronger CSRF defenses rather than used alone.