Monday, April 18, 2016

Run Inline Scripts And External JS with Content Security Policy

“In general, CSP works as a black/whitelisting mechanism for resources loaded or executed by your extensions. Defining a reasonable policy for your extension enables you to carefully consider the resources that your extension requires, and to ask the browser to ensure that those are the only resources your extension has access to. These policies provide security over and above the host permissions your extension requests; they're an additional layer of protection, not a replacement.”

To set content security policy add following meta tag in head
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'unsafe-inline' 'unsafe-eval'">

If we will use Content Security Policy then Inline JavaScript will not be executed. This restriction bans both inline <script> blocks and inline event handlers (e.g. <button onclick="...">).

For Whitelist Inline Scripts and External JS…

CSP Level 2 offers backward compatibility for inline scripts by allowing you to whitelist specific inline scripts using either a cryptographic nonce (number used once) or a hash. Although this may be cumbersome in practice, it is useful in a pinch.

To use a nonce, give your script tag a nonce attribute. Its value must match one in the list of trusted sources. For example

Add nonce in meta tag  (For Inline) :
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'unsafe-inline' 'unsafe-eval' 'nonce-EDNnf03nceIOfn39fn3e9h3sdfa'">

Add nonce attribute in script tags :
<script nonce="EDNnf03nceIOfn39fn3e9h3sdfa">
    alert('Hello, world.');

For External JS and Bundling JS we need to define Domain Name or CDN URL in Meta tag (We can define both also) :
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'unsafe-inline' 'unsafe-eval';style-src 'unsafe-inline' 'unsafe-eval'">


“It is better to take all Inline scripts into External JS and don’t use nonce and Instead use Domain URL for calling External JS. Because by using nonce any hacker can call Script Injection in Browser by using same nonce.”

For more details use this :
Post a Comment

Find a cool free stuff everyday

Giveaway of the Day

Hiren Bharadwa's Posts