Home > database >  I added Content-Security-Policy to an new angular project and cleared everything but when I run the
I added Content-Security-Policy to an new angular project and cleared everything but when I run the

Time:07-19

So I added Content-Security-Policy in the index.html on my angular project.

index.html

<!doctype html>
<html lang="en">

<head>
 <meta charset="utf-8">
 <meta http-equiv="Content-Security-Policy"
       content="default-src 'self';"
 >
 <title>Csptest</title>
 <base href="/">
 <meta name="viewport" content="width=device-width, initial-scale=1">
<!--  <link rel="icon" type="image/x-icon" href="favicon.ico">-->
</head>
<body>
 <app-root></app-root>
</body>
</html>

Also cleared everything present in the app.component.html.

app.component.html

<h2>App component works</h2>

app.component.ts

import { Component } from '@angular/core';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent {
 title = 'csptest';
}

But when I run the project it gets compiled but when I go to localhost:4200 it says

Refused to apply inline style because it violates the following Content Security Policy directive: "default-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-l5BdY8iHQaD9T7HFC/wOySvJobC7DMB33NJOSw ToWw='), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'style-src' was not explicitly set, so 'default-src' is used as a fallback

So I am a bit confused here, if everything has been removed from app.component.html and no other components exists in the project then why is this error showing up.

CodePudding user response:

As the error message states

  • you have to either add 'unsafe-inline' (ok for style-src but not for script-src or default-src)

    Content-Security-Policy: style-src 'unsafe-inline'

  • or use a nonce/hash, like this:

    Content-Security-Policy: style-src 'nonce-0123456789'

When using a nonce, you have to reference it in the <style> tag:

<style nonce="0123456789">
    body { background: red; }
</style>

This approach requires you to generate a new nonce on every page load and might be harder to implement.

See https://content-security-policy.com/examples/allow-inline-style/ for more information.

CodePudding user response:

Could you share your index.html, app.component.ts and app.component.html contents ?

Or simply recreate a new project.

  • Related