The form-action Directive
What you'll learn: How to use the form-action directive to control where forms on your page can submit data, preventing malicious redirects.
What It Does
The form-action directive in Content Security Policy (CSP) restricts which URLs your HTML forms can use as their action attribute. This prevents attackers from injecting forms or modifying existing ones to send user data (like passwords or credit card numbers) to unauthorized endpoints.
Think of it like putting a bouncer at the exit of your building who only allows packages to be sent to pre-approved addresses. Even if someone inside tries to redirect a shipment elsewhere, the bouncer checks against the approved list first.
Why It Matters
Without form-action, an attacker who injects HTML into your page could create a fake login form that posts credentials to their own server. Even if your CSP blocks scripts, they could still harvest data through form submissions. This directive closes that gap.
How to Use It
Add form-action to your CSP header with the allowed destinations:
Content-Security-Policy: form-action 'self' https://api.yoursite.com
This example allows forms to submit only to:
- Your own domain (
'self') - Your specific API endpoint
If a form tries to post anywhere else, the browser blocks it.
Common Patterns
- Same-origin only:
form-action 'self'(most restrictive, safest) - Specific endpoints:
form-action 'self' https://payment-processor.com - Block all forms:
form-action 'none'(useful for static content sites)
Key Takeaway: The form-action directive prevents forms from submitting to unauthorized URLs, protecting user data even when attackers inject HTML without scripts.