javascriptasp.netcontent-security-policynonce

ASP.Net form - Content-Security-Policy nonce value is not working for inline script


net empty webform project and add 1 button, 1 inline script (1 function used in button) and desclared 1 meta tag for Content-Security-Policy settings.

My intention is want to use nonce logic in my aspx file, inline script must include~

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication4.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' ; script-src 'self' 'nonce-random' 'unsafe-eval'; "/>
    <script type="text/javascript" nonce="random">
        function Test() {
            alert("testing");
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
           <div>
            <button type="button" onclick="Test()">Test</button>
        </div>
    </form>
</body>
</html>

My expected result:

Launched website, click button and return me the alert message.

Actual result: Nothing happened. Here is log message from console of developer tool of browser:

Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' 'nonce-random' 'unsafe-eval'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the 'unsafe-hashes' keyword is present.

My intention is want to use nonce logic in my aspx file, inline script must include~ Click button can see the alert message


Solution

  • You have added the nonce to inline script, but it is likely the inline event handler (onclick="Test()") which is causing the error. Try replacing this with an event listener as the inline event handler is not a nonceable element.