What is Content Security Policy (CSP)?
1. What is CSP?
Content Security Policy (CSP) is a browser security mechanism that allows a web application to specify which sources the browser is allowed to load or execute content from.
It is mainly used as an additional defense against attacks such as:
- Cross-Site Scripting (XSS)
- Malicious script injection
- Loading unauthorized external resources
- Clickjacking, with appropriate directives
The server sends a response header such as:
Content-Security-Policy: default-src 'self'; script-src 'self'
This tells the browser:
By default, load resources only from this application's own origin, and execute scripts only from this application's own origin.
2. Simple Example
Suppose your Angular application is:
https://www.myapp.com
An attacker somehow injects:
<script src="https://evil.example/hack.js"></script>
Without an effective CSP, the browser may attempt to load that script.
With:
Content-Security-Policy: script-src 'self'
the browser checks:
Script requested:
https://evil.example/hack.js
↓
CSP says:
script-src 'self'
↓
evil.example != myapp.com
↓
BLOCKED
So CSP provides another layer of defense even if an injection vulnerability exists.
3. Full Simple Angular + ASP.NET Core Example
For an Angular + ASP.NET Core application, CSP is typically delivered as an HTTP response header by the web server or ASP.NET Core application serving the page.
ASP.NET Core Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
// Content Security Policy
app.Use(async (context, next) =>
{
context.Response.Headers.Append(
"Content-Security-Policy",
"default-src 'self'; " +
"script-src 'self'; " +
"style-src 'self'; " +
"img-src 'self' data:; " +
"font-src 'self'; " +
"connect-src 'self' https://localhost:7001; " +
"object-src 'none'; " +
"base-uri 'self'; " +
"frame-ancestors 'none';");
await next();
});
app.UseAuthorization();
app.MapControllers();
app.Run();
The important part is:
context.Response.Headers.Append(
"Content-Security-Policy",
"...");
The browser receives this header and enforces the policy.
4. Understanding the Policy
Our example contains:
default-src 'self';
script-src 'self';
style-src 'self';
img-src 'self' data:;
font-src 'self';
connect-src 'self' https://localhost:7001;
object-src 'none';
base-uri 'self';
frame-ancestors 'none';
Let's understand each directive.
default-src
default-src 'self'
This provides a fallback policy for resource types without a more specific directive.
'self' means:
Allow resources from the same origin.
For example:
https://www.myapp.com
5. script-src
script-src 'self'
Controls where JavaScript can come from.
Allowed:
https://www.myapp.com/main.js
Potentially blocked:
https://evil.example/hack.js
This is one of the most important CSP directives for XSS mitigation.
6. style-src
style-src 'self'
Controls permitted stylesheet sources.
For example:
<link
rel="stylesheet"
href="/styles.css">
is allowed.
An external stylesheet from an unlisted origin would be blocked.
Depending on how the application generates styles, Angular applications may require a more carefully designed style policy rather than blindly using a strict example policy.
7. img-src
img-src 'self' data:
This permits images from the application's own origin and data: URLs.
For example:
https://www.myapp.com/images/logo.png
is allowed.
If your application loads article images from another domain, you need to explicitly allow that origin.
For example:
img-src 'self' https://images.example.com data:
8. connect-src
This directive is particularly important for Angular applications.
Angular uses HttpClient to communicate with APIs.
Suppose:
Angular:
https://www.myapp.com
ASP.NET Core API:
https://api.myapp.com
Then CSP might contain:
connect-src 'self' https://api.myapp.com
This allows Angular to connect to:
https://api.myapp.com
but not arbitrary servers.
For example:
Angular
|
| HttpClient
v
https://api.myapp.com
✓
https://evil.example
✗
connect-src can also affect technologies such as WebSocket connections.
9. object-src
A common secure setting is:
object-src 'none'
It disables plugin/object resources such as:
<object>
when the application doesn't need them.
Reducing unnecessary resource types reduces attack surface.
10. base-uri
Consider:
base-uri 'self'
This restricts what can be used as the document's base URL.
It helps prevent malicious manipulation involving:
<base>
11. frame-ancestors
A strong policy may include:
frame-ancestors 'none'
This means:
Don't allow other pages to embed this page in a frame.
It provides protection against framing-based attacks such as clickjacking.
If your application legitimately needs to be embedded, the policy must be adjusted accordingly.
12. CSP and XSS
This is the most important relationship.
Suppose an attacker injects:
<script>
stealData();
</script>
A well-designed CSP can prevent unauthorized script execution.
Conceptually:
Attacker injects script
↓
Browser encounters script
↓
Check CSP
↓
Is this script permitted?
/ \
YES NO
| |
Execute Block
Therefore CSP provides defense in depth.
13. CSP Does NOT Replace Angular's XSS Protection
Don't think:
We have CSP
↓
We don't need XSS protection
Instead:
Angular escaping/sanitization
+
Safe coding
+
Server-side sanitization
+
CSP
↓
Defense in depth
CSP is an additional layer, not a replacement for fixing XSS vulnerabilities.
14. What About Inline JavaScript?
A strict CSP such as:
script-src 'self'
doesn't generally permit arbitrary inline scripts such as:
<script>
alert('Hello');
</script>
Some applications weaken CSP using:
'unsafe-inline'
For example:
script-src 'self' 'unsafe-inline'
But 'unsafe-inline' significantly reduces the XSS protection CSP can provide.
So avoid adding:
'unsafe-inline'
merely to make CSP errors disappear.
15. CSP Nonce
When legitimate inline scripts are unavoidable, a stronger approach is to use a nonce.
The server generates a cryptographically random value for the response.
For example:
Content-Security-Policy:
script-src 'self' 'nonce-AbC123...'
Then an authorized script has the matching nonce:
<script nonce="AbC123...">
// trusted script
</script>
The browser compares them:
CSP
nonce-AbC123
|
| matches
v
<script nonce="AbC123">
|
v
Allowed
An injected script without the valid nonce is blocked.
In production, the nonce must be unpredictable and generated per response; don't hard-code a fixed nonce.
16. CSP Hash
Another option is a cryptographic hash.
Conceptually:
script-src 'sha256-...'
The browser calculates the script's hash.
Inline Script
↓
Calculate hash
↓
Compare with CSP
/ \
Match No match
↓ ↓
Allow Block
This is useful for known, static inline content.
17. CSP Report-Only Mode
Before enforcing a strict CSP in production, you can test it using:
Content-Security-Policy-Report-Only: ...
The browser evaluates the policy and reports violations without enforcing the same blocking behavior as an enforced CSP.
This is useful because a new CSP can accidentally block legitimate application resources.
A common rollout approach is:
Create policy
↓
Report-Only
↓
Observe violations
↓
Fix legitimate dependencies
↓
Test
↓
Enforce CSP
18. CSP vs CORS
These are different.
CSP
Controls what resources your page is allowed to load/connect to/execute.
My Angular page
↓
What resources can it use?
↓
CSP
CORS
Controls whether a server permits browser-based cross-origin access to its responses.
Angular
↓
Calls another origin
↓
Does API allow this origin?
↓
CORS
So:
CSP != CORS
They complement each other.
19. CSP vs XSS vs CSRF
| Security concept | Purpose |
|---|---|
| XSS protection | Prevent attacker-controlled script execution |
| CSP | Restrict what browser content/resources can execute/load |
| CSRF protection | Prevent forged authenticated requests |
| CORS | Control browser cross-origin access |
| Authentication | Establish who the user is |
| Authorization | Determine what the user may do |
This distinction is very useful in interviews.
20. Example for Angular + ASP.NET Core
Suppose your architecture is:
Angular
https://www.jntech.in
|
| HTTPS
v
ASP.NET Core API
https://api.jntech.in
A conceptual CSP could contain:
default-src 'self';
script-src 'self';
style-src 'self';
img-src 'self' data: https://images.example.com;
connect-src 'self' https://api.jntech.in;
object-src 'none';
base-uri 'self';
frame-ancestors 'none';
The important Angular-specific part is often:
connect-src
because the SPA needs permission to communicate with its APIs.
21. Key Points
1. CSP is a browser security policy
It is normally delivered using:
Content-Security-Policy
2. CSP helps mitigate XSS
It restricts which scripts and resources the browser can execute or load.
3. 'self' means same origin
script-src 'self'
means scripts from the application's own origin are permitted.
4. connect-src is important for Angular
It controls destinations Angular can connect to through mechanisms such as HttpClient.
5. Avoid weakening CSP unnecessarily
Especially avoid blindly adding:
'unsafe-inline'
or:
'unsafe-eval'
just to remove browser errors.
6. Nonces and hashes can authorize specific scripts
They provide stronger alternatives when legitimate inline scripts are necessary.
7. CSP is defense in depth
CSP does not replace Angular sanitization, secure coding, backend validation, or proper authentication/authorization.
Interview Questions and Answers
1. What is Content Security Policy?
Answer:
CSP is a browser security mechanism, usually configured through an HTTP response header, that restricts which scripts, styles, images, connections, and other resources a page may load or execute.
2. Why is CSP used?
Answer:
CSP is primarily used as defense in depth against XSS and malicious content injection by restricting where executable scripts and other resources may come from.
3. What does 'self' mean in CSP?
script-src 'self'
means scripts are allowed from the page's own origin.
4. What is script-src?
It defines which JavaScript sources the browser is allowed to execute/load.
Example:
script-src 'self'
5. What is connect-src?
It defines which destinations the page may connect to using mechanisms such as HTTP requests and WebSockets.
For Angular, it commonly includes the ASP.NET Core API origin.
6. What is default-src?
It is the fallback source policy used when a more specific resource directive hasn't been specified.
Example:
default-src 'self'
7. What is a CSP nonce?
A nonce is a cryptographically random, per-response value used to authorize specific scripts.
The nonce specified by CSP must match the nonce on the permitted script.
8. What is Content-Security-Policy-Report-Only?
It allows you to evaluate a CSP and collect violation information before fully enforcing the policy, making it useful when introducing CSP to an existing application.
9. Does CSP replace Angular XSS protection?
No.
CSP is an additional security layer. Angular's normal escaping/sanitization, safe coding practices, and appropriate server-side sanitization are still necessary.
10. What is the difference between CSP and CORS?
CSP controls what resources your web page can load, execute, or connect to.
CORS controls whether a server allows browser-based cross-origin access to its resources.
Interview Quick Answer
Content Security Policy (CSP) is a browser security mechanism configured mainly through the
Content-Security-PolicyHTTP response header. It restricts which scripts, styles, images, APIs, and other resources an Angular application can load or execute. CSP provides defense in depth against XSS and content injection attacks. Important directives includedefault-src,script-src,style-src,img-src,connect-src,object-src, andframe-ancestors.