What Is Content Security Policy (CSP) And How Can It Be Implemented In Angular?
Last Updated :
14 Aug, 2024
Content Security Policy (CSP) is a security feature that helps to protect your web applications from various types of attacks, such as Cross-Site Scripting (XSS) and data injection attacks. CSP is a browser feature that allows web developers to define a list of approved content sources that the browser should trust, reducing the risk of malicious content being executed on the website.
CSP works by providing a layer of security that helps prevent unauthorized scripts from running. It can be configured via HTTP headers or meta tags, instructing the browser on what content to load and what to block. This is particularly important in modern web applications where content can come from various sources, including external APIs, advertisements, and user-generated content.
Key Features of CSP
- Script Control: CSP allows you to specify which scripts are allowed to run on your website.
- Style Control: Similar to scripts, you can control which stylesheets can be applied.
- Content Control: You can restrict the loading of images, fonts, media, and other resources.
- Frame Control: CSP can restrict what content can be embedded via <iframe> tags.
- Reporting: CSP can be configured to report violations to a specified endpoint, allowing developers to monitor and act on potential security issues.
What are CSP Directives?
Directives are the core of a CSP policy. CSP accepts a set of directives, either in HTTP headers or meta tags in the HTML, that specify which content is allowed to load and execute on the web page. Some of Common CSP Directives include "default-src", "script-src", "style-src", etc.
Configuring CSP in HTTP headers is an important step in enhancing the security of your web application. We can add CSP directives in the HTTP headers itself so that we can ensure that all the responses and the HTML web pages have the directives set. CSP is the primary header used to enforce CSP rules.
We can add the CSP directives in a node.js server like below:
//server.js
const express = require('express');
const helmet = require('helmet');
const app = express();
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'"],
fontSrc: ["'self'"]
}
})
);
We can set the CSP directives in the meta tag as well. To set the directives in an angular application. The CSP meta tag allows you to define a Content Security Policy in HTML <head> Section. Configuring CSP with meta tags is a good way to implement and test Content Security Policies directly within your HTML documents.
Step 1: Setup an angular project using the below commands:
ng new angular-csp
cd angular-csp
Folder Structure
Folder StructureDependencies
"dependencies": {
"@angular/animations": "^18.0.0",
"@angular/common": "^18.0.0",
"@angular/compiler": "^18.0.0",
"@angular/core": "^18.0.0",
"@angular/forms": "^18.0.0",
"@angular/platform-browser": "^18.0.0",
"@angular/platform-browser-dynamic": "^18.0.0",
"@angular/router": "^18.0.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Step 2: Update index.html file
Add CSP directives in the index.html file present in "src" directory under <meta> tag.
HTML
<! --- index.html --->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>AngularCsp</title>
<base href="/" />
<meta name="viewport"
content="width=device-width,
initial-scale=1" />
<link rel="icon" type="image/x-icon"
href="favicon.ico" />
<meta http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'; style-src 'self';
img-src 'self' data:; font-src 'self'; connect-src 'self';" />
</head>
<body>
<app-root></app-root>
</body>
</html>
Step 3: Run the application
Start the application server using the below command:
ng serve
Output:
Handling Angular-Specific Considerations
Angular Applications are built with component-based-archietecture, which often include dynamic content, which can present challenges for CSP. To implement CSP in Angular application, we can use the angular "ng-csp" directive in the html tag, which can take in the value of "no-unsafe-eval" or "no-inline-style" which when set avoids the use of eval function and inline stylings in the code respectively.
Testing and Monitoring CSP
Implementation of CSP is very important in order to secure Angular Applications from various attacks. However, after setting up CSP, it is important to test and monitor its effectiency. We can test whether CSP is actually working or not by including a script in the HTML page whose source is not mentioned in the CSP directives, and checking if the script loads. We can also set CSP to report or log CSP violations to a specific endpoint using "report-to" CSP directive.
Example:
Content-Security-Policy: default-src 'self'; report-to /csp-violation-report-endpoint/
Similar Reads
What is the difference between ng-app and data-ng-app in AngularJS ?
In web application development, AngularJS is one of the most favorite dynamic JavaScript frameworks that has HTML through script tags, enabling us to augment the HTML attributes using the directives and facilitating the data binding through the expressions. In this article, we will see the concepts
5 min read
What are some important practices to secure an Angular application ?
In this article, we will see how we can secure our angular application from common types of vulnerabilities which can exploit the angular application. Also, we will see some best practices to protect such applications. Angular is a JavaScript development framework, which programmers extensively use
5 min read
How to include a JavaScript File in Angular and call a Function from that Script ?
In this article, we will learn how to include a JavaScript file in Angular and call a function, defined inside that file, from that script. In Angular, we can include JavaScript script files to import some features or utilize some external libraries or pieces of code, which can be a great asset whil
4 min read
HTTP headers | Content-Security-Policy
The Content Security Policy response header field is a tool to implement defense in depth mechanism for protection of data from content injection vulnerabilities such as cross-scripting attacks. It provides a policy mechanism that allows developers to detect the flaws present in their application an
3 min read
Introduction To Components And Templates in Angular
Angular is a powerful framework for building dynamic, single-page web applications. One of the core concepts that make Angular so effective is its use of components and templates. Components and templates are the building blocks of any Angular application, allowing developers to create reusable, mai
6 min read
How to use AngularJS to Display HTML content value ?
The ng-bind-html Directive is used to bind the innerHTML of an HTML element to application data and remove dangerous code from the HTML string. The $sanitize service is a must for the ng-bind-html directive. It is supported by all HTML elements. Syntax: <element ng-bind-html="expression"> Cont
2 min read
How can AngularJS controller inherit from another controller in the same Module ?
In the AngularJS Framework, Controller Inheritance allows the controller to inherit the properties, methods, and other kinds of utilities from the other controller in the same module. It is nothing but the inheritance concept of OOP. So, in AngularJS, to perform the controller inheritance, we can us
5 min read
What are the main building blocks of an Angular Application?
Angular is a widely used open-source front-end framework used to build dynamic web applications. It consists of several key building blocks that work together to create scalable, and maintainable applications. In this article, we will explore all the main building blocks of an Angular application an
8 min read
How to set, get and clear cookies in AngularJS ?
In this article, we will see how to set, get & clear the Cookies in AngularJS, along with understanding the basic usage through the implementation. In AngularJS, we need to use angular-cookies.js to set, get and clear the cookies. You can use the live CDN link for this: https://cdnjs.cloudflare.
2 min read
How to limit the length of a string in AngularJS ?
Validation of fields is an important process while developing a dynamic web application. In various aspects of security, the validation is quite important. Along with this, the restriction of the limit to the length of a string is also an important process that helps to include the constraint for th
5 min read