andrewlock / NetEscapades.AspNetCore.SecurityHeaders

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

Possible to change CSP after it has been built? #64

Open ghost opened 5 years ago

ghost commented 5 years ago

Is there a way to change the CSP after it has been built with AddContentSecurityPolicy? As far as I can see the only option is overwrite it by calling the method again but I am utilising this in a common library of my own and I would like the consumer of my common library to be able to change the policy from the default that is set.

andrewlock commented 5 years ago

Hi, IIRC there's no way to change the CSP after it's been built, but depending on how you design your library, that may not be necessary. Can you give an example of what you're trying to do?

nbarbettini commented 4 years ago

Maybe a different way of looking at it would be: split configuration off into ConfigureServices and just apply the middleware in Configure, following the pattern of other common middleware.

That would provide the ability to compose with the Options pattern to dynamically change the configuration in an idiomatic way.

andrewlock commented 4 years ago

Ironically, that's the approach I used to have, and for essentially this reason. I changed it way back when to simplify registration for most cases 🙂

It wouldn't be too hard to whack the HeaderPolicyCollection onto an IOptions<> object, but your couldn't load it directly with the current design. Plus, even if I updated that so you could, you'd lose a huge benefit of the library in my eyes - not relying on easily-mistyped strings.

Moving the HeaderPolicyCollection to an options object would allow you to use IConfigureServices to switch between collections based on your own IOptions types, but that's pretty convoluted and I doubt many people would grasp that.

Either way it would require a fairly big redesign - currently the lib tries to calculate as much as it can upfront. If it has to rebuild that every request (because of potential changes in options) that's either a lot more allocations, or a lot more work to avoid those allocations! For, in my opinion, little gain.

Ignoring the options part for now though, I think it would still be possible to have different policies applied to different endpoints again, it just requires a bit of work. Is that something you need @nbarbettini ?

nbarbettini commented 4 years ago

@andrewlock Thanks for your quick reply, and sorry for the delay on my side! It wasn't urgent, more of a curiosity I was exploring.

I've used Finbuckle.Multitenant for a few applications and it has the concept of per-tenant options that are set up during ConfigureServices time. So in that case, it's not really about different CSP per endpoint as much as per-tenant in a multitenant scenario.