ASP.NET form - Content-Security-Policy nonce value is not working on linkbutton

88 Views Asked by At

In my existing project, I have a link button control in .aspx, which has many logic in the click event in the aspx.cs file. My intention is that the link button click can work as well after Content-Security-Policy removed the 'unsafe-inline' and 'nonce-random' is added.

The link button will be rendered to become htmlAnchorElement and has a href value will have the doPostBack function which is inline execution, so I think it violates the CSP. Is there any solution to this issue? Or is it possible to call the server side click event function from front end and pass the CSP rule which is nonce-random?

Is __doPostBack not allowed?

enter image description here

Default.aspx:

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Link button click violete the CSP nonce-random</title>
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'nonce-random'" />
</head>
    <script type="text/javascript" nonce="random">
        document.addEventListener('DOMContentLoaded', () => {
            let btn = document.getElementById('button001');
            btn.addEventListener('click', () => {
                // handle the click event
                alert('clicked');
            });
        });
    </script>
<body>
    <form id="form1" runat="server">
        <div>
            <p>Must use nonce CSP setting in my requirement...</p>
            <p>My issue is my linkbutton control violates the Content Security Policy... </p>
            <asp:LinkButton runat="server" ID="linkButton001" Text="LinkButton,click me.." nonce="random"> </asp:LinkButton>
            <br />
            <br />
            <asp:Button runat="server" ID="button001" Text="Button Test"/>
        </div>
    </form>
</body>
</html>

Default.aspx.cs:

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.linkButton001.Click += new EventHandler(this.linkButton001_Click);
    }

    private void linkButton001_Click(object sender, EventArgs e)
    {
        // in actual code, i have many logic in here.
        ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('linkButton001_Click clicked.');", true);
    }
}
  • Linkbutton can work as well in CSP nonce-random (without unsafe-inline)

  • Linkbutton logic can be triggered in aspx.cs after being clicked in CSP nonce-random (without unsafe-inline)

Is there any solution or alternative workaround for this issue?

Thank you.

0

There are 0 best solutions below