madskristensen / WebEssentials.AspNetCore.ServiceWorker

Other
339 stars 61 forks source link

Inline service worker script fails to register with restrictive Csp policy #30

Closed ashleybroughton closed 6 years ago

ashleybroughton commented 6 years ago

Using a content-security-policy of 'self' for script sources will make the <script> tag added by the following line of code to fail. At current, there appears to be no built-in way to include a nonce for this script tag.

public void ConfigureServices(IServieCollection services)
    // ...
    services.AddProgressiveWebApp();
}

How do we enable this script tag to work without allowing unsafe-inline for script sources in Csp?

ashleybroughton commented 6 years ago

I see this option was added 14 days ago in #34, but I'm not sure whether I'm using it incorrectly, or whether it just doesn't work as expected.

services.AddProgressiveWebApp(new PwaOptions { EnableCspNonce = true });

this produces the following script tag

<script nws-csp-add-nonce='true'>'serviceWorker'in navigator&&navigator.serviceWorker.register('~/serviceworker')</script></body>

but I would have expected it to produce the following

<script nonce='b2K5eO1tE5gODUiQfw4q'>'serviceWorker'in navigator&&navigator.serviceWorker.register('~/serviceworker')</script></body>
ashleybroughton commented 6 years ago

It seems that the NWebSec CspNonceTagHelper inherits TagHelper without overriding Order which makes it default to a value of 0.

Whereas ServiceWorkerTagHelperComponent overrides the Order with a value of 100.

As TagHelpers are executed in lowest order first, the script tag for the service worker will not exist when the NWebSec TagHelper executes.

RaceProUK commented 4 years ago

I'm currently seeing this issue in a ASP.NET Core 3.1 app I'm building, and I'm wondering whether it's a genuine issue or if I'm just doing something wrong.

The code I'm using to set up the manifest and service worker is below:

            services.AddProgressiveWebApp(new PwaOptions
            {
                CacheId = "<cacheId>",
                Strategy = ServiceWorkerStrategy.Minimal,
                OfflineRoute = "offline.htm",
                RoutesToPreCache = "/Home/Index",
                RegisterServiceWorker = true,
                RegisterWebmanifest = true,
                EnableCspNonce = true
            });

This results in this HTML snippet:

<script nws-csp-add-nonce='true'>'serviceWorker'in navigator&&navigator.serviceWorker.register('/serviceworker', { scope: '/' })</script>

instead of the expected

<script nonce='<nonceValue>'>'serviceWorker'in navigator&&navigator.serviceWorker.register('/serviceworker', { scope: '/' })</script>

Package versions in use: WebEssentials.AspNetCore.ServiceWorker 1.0.59 NWebsec.AspNetCore.Mvc.TagHelpers 3.0.0