user14801358
user14801358

Reputation:

Add nonce to style inline

<div .... style="background-color: #fff" ..... </div>

How to add nonce (CSP) to this style? It is not between style tags as you see.

Upvotes: 8

Views: 12128

Answers (2)

Daham Akl
Daham Akl

Reputation: 628

There are the most efficient and recomended ways to add CSP to an Html web project or for a ReactJS-based project.

Add CSP resource to Meta tag of the Head tags of the Main Html file.

Example Main HTML file:

<html>
<head>
    <meta http-equiv="Content-Security-Policy" content="directives">
    <!-- Other meta tags, title, etc. -->
</head>
<body>
    <!-- Your HTML content -->
</body>
</html>

Modifyed version of Meta tag:

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' https://cdn.example.com; style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' https://www.example.com">

Use style-src to specify the following URLs for the Styles only.

Also, unsafe-hashes supports to apply CSP resources.

Upvotes: -1

Halvor Sakshaug
Halvor Sakshaug

Reputation: 3455

Only style and script are nonceable elements in CSP level 2, https://www.w3.org/TR/CSP2/#script-src-the-nonce-attribute. You might be able to do this in CSP level 3, but unless you can target only specific browsers that support it, you should move your style to a style tag with nonce or a css file.

Edit 2024-02-01: In CSP level 3, which has good browser support now, you can use 'unsafe-hashes' in addition to the hash of the attribute code to allow attribute styles/scripts. Unless you only have a few attributes with static content that need hashes you should still try to move it.

Upvotes: 8

Related Questions