juunas11 / aspnetcore-security-headers

Middleware for adding security headers to an ASP.NET Core application.
MIT License
264 stars 42 forks source link

Nonce is empty #68

Closed spaasis closed 1 year ago

spaasis commented 1 year ago

Hi, and thanks for the great package! This is a weird one.

Nuget version 4.0.1, ASP NET Core 6.

ViewImports:

@using WebUI
@namespace WebUI.Pages
@addTagHelper *, Joonasw.AspNetCore.SecurityHeaders
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@using Microsoft.AspNetCore.Mvc.Localization
@using Microsoft.Extensions.Localization

Startup:

            app.UseMiddleware<SecurityHeadersMiddleware>();

            app.UseCsp(csp => {
                csp.ByDefaultAllow.FromNowhere();
                csp.AllowScripts
                    .FromSelf()
                    .AddNonce();
                csp.AllowStyles
                    .FromSelf()
                    .AddNonce(); 
                csp.AllowImages
                    .FromSelf();
                csp.AllowFonts
                    .FromSelf();
            });

....

services.AddCsp();

_Layout.cshtml (with nonce as title for testing):

<head>
    <title>@Nonce.GetNonce()</title>

    <script src="~/lib/jquery/dist/jquery.min.js" asp-add-nonce="true"></script>

Generated html:

<title>dCOv2X2ZpvsHAVQy4NPb4m2uslSe1azP+bdVjkbGDtk=</title>
<script src="/lib/jquery/dist/jquery.min.js" nonce=""></script>

I set a breakpoint to the NonceTagHelper Process and it actually hits, runs through the output.Attributes.Add("nonce", _nonceService.GetNonce()); and I tested that the _nonceService.GetNonce() actually returns the nonce.

So everything seems to work as intended, expect that the nonce is not output to html. I'm dumbstruck, especially when the breakpoint shows that the code is actually ran.

Would you happen to have any ideas?

tmog commented 1 year ago

Some browsers hide nonce attribute values when viewing html in the inspector. Is the nonce still missing if you "view source" instead?

spaasis commented 1 year ago

That was it, thanks! What a weird behavior..