style-src-attr
Thestyle-src-attr
directive specifically controls inline style attributes in HTML elements (like style="..."
) in your web application. This directive provides granular control over inline styles, allowing you to enforce stricter security policies for style attributes independently of other style sources.
Recommended Values
'none' No sources are allowed
'sha256-<hash>' Allows the resource to be loaded and executed
Recommended style-src-attr configuration (most secure)
Content-Security-Policy: style-src-attr 'none';
Relationship with style-src
Thestyle-src-attr
directive specifically controls inline style attributes, while the style-src
directive is a fallback that controls all style sources. When style-src-attr
is not specified:
- The browser falls back to the
style-src
directive - If
style-src
is also not specified, it falls back todefault-src
Tips & Tricks
Using 'none' is recommended as it completely blocks inline style attributes, enforcing better separation of concerns.
The 'unsafe-hashes' keyword allows inline style attributes with a specific hash. See the values section for more information.
Inline styles can make maintenance harder and may pose security risks. Consider using external stylesheets instead.
Possible Values
'none'
: No inline style attributes are allowed'report-sample'
: Includes a sample of the violating code in violation reports- Nonces:
'nonce-<random>'
for specific inline style attributes - Hashes:
'sha256-<hash>'
for specific inline style attributes - ⚠️
'unsafe-inline'
: Allows all inline style attributes (insecure)
Example Configurations
Example policy with nonce
Allows inline styles from the same origin and with a hash
Content-Security-Policy: style-src-attr 'sha256-jkH3R37FjM3jF837j3M733j8F73Mf';
Allowed
<!-- allowed by hash -->
<p style="color: red;">Red text</p>
Blocked
<!-- blocked as no 'unsafe-inline' and hash doesn't match -->
<span style="font-weight: bold;">Bold text</span>
Additional Information
- The
style-src-attr
directive is part of CSP Level 3 - It provides more granular control over inline styles compared to
style-src
- Using this directive can help enforce better coding practices by discouraging inline styles
- Consider using CSS classes and external stylesheets instead of inline styles
Related Resources
External Articles
- MDN Web Docs: style-src-attr
- OWASP: Content Security Policy Cheat Sheet
- Google Web Fundamentals: Content Security Policy