I'm spending some time with CSP in the interest of making my Angular 5 application as secure as possible, but struggling to get it to work.
I have enabled CSP
using NWebSec
, as follows:
app.UseCsp(options =>
{
options.DefaultSources(s => s.Self());
options.ScriptSources(s => s.Self());
options.StyleSources(s => s.Self().CustomSources("stackpath.bootstrapcdn.com"));
}); // Use Content Security Policy
I have built the angular application using:
ng build --aot --prod
The ASP.Net
Core application is hosting the (built) Angular application, using the app.UseStaticFiles()
middleware.
I have read through a few articles and tried to find a straight answer on how to get this working but I can't get passed this error, which originates from /main.ae5fbeccd9ff1305a55c.js:
Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' stackpath.bootstrapcdn.com". Either the 'unsafe-inline' keyword, a hash ('sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='), or a nonce ('nonce-...') is required to enable inline execution.
I believe that Angular is creating the code which causes these errors and the solution is to use the "--aot" command when building the application, but that's not working for me.
I have tried this with Angular 5 and Angular 6 (Even tried using a new Angular project). Same issue.
My question is: Is there currently a recommended way to get Angular 5/6 working with CSP, without sacrificing security? and if not, what is the next best thing?
Cheers
Additional Details: Index.html (Default build Angular 6 application)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Default Angular App</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="styles.34c57ab7888ec1573f9c.css">
</head>
<body>
<app-root></app-root>
<script type="text/javascript" src="runtime.6afe30102d8fe7337431.js"></script>
<script type="text/javascript" src="polyfills.2903ad11212d7d797800.js"></script>
<script type="text/javascript" src="main.ae5fbeccd9ff1305a55c.js"></script>
</body>
</html>
Processing of the CSS in Angular isn't compliant with modern security standards, as styles remain inline in all the components (here is a ticket for that).
So far we have to put up with unpleasant style-src 'unsafe-inline'
directive in the CSP headers.
For a simple app with Google fonts, the CSP header may look like
Content-Security-Policy: "default-src 'self'; style-src 'self' fonts.googleapis.com 'unsafe-inline'; font-src 'self' fonts.gstatic.com";
This post goes into details of the CSP policies in Angular.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With