andrewlock / NetEscapades.AspNetCore.SecurityHeaders

Small package to allow adding security headers to ASP.NET Core websites
MIT License
701 stars 73 forks source link

Make nonce generation lazy #198

Closed andrewlock closed 2 months ago

andrewlock commented 2 months ago

With the changes to having named policies, it's no longer obvious ahead of time whether nonce generation will be required, so we need to always generate it.

To avoid the overhead of creating the nonce in cases where we don't need it, switch to creating it lazily with the call to HttpContext.GetNonce(). The code in there isn't thread safe, but then HttpContext isn't thread safe in general so it probably doesn't matter.

Note that means you must use the GetNonce() extension to retrieve the nonce, you can't just grab it out directly. While technically not a breaking change it oculd be if people are relying on the implementation