DEV Community

丁久
丁久

Posted on • Originally published at dingjiu1989-hue.github.io

Content Security Policy

This article was originally published on AI Study Room. For the full version with working code examples and related articles, visit the original post.

Content Security Policy

Content Security Policy

Content Security Policy

Content Security Policy

Content Security Policy

Content Security Policy

Content Security Policy

Content Security Policy

Content Security Policy

Content Security Policy

Content Security Policy

Introduction

Content Security Policy (CSP) is a browser security mechanism that mitigates Cross-Site Scripting (XSS), data injection, and clickjacking attacks. By defining a whitelist of trusted content sources, CSP prevents the browser from executing malicious scripts or loading unauthorized resources.

CSP Directives

CSP uses HTTP headers with directives that control specific resource types.

Content-Security-Policy:

default-src 'self';

script-src 'self' https://cdn.trusted.com;

style-src 'self' 'unsafe-inline';

img-src 'self' data: https://*.cloudfront.net;

connect-src 'self' https://api.example.com;

font-src 'self' https://fonts.gstatic.com;

frame-src 'none';

object-src 'none';

base-uri 'self';

form-action 'self';

Key directives:

| Directive | Controls | Example | |-----------|----------|---------| | default-src | Fallback for all resource types | default-src 'self' | | script-src | JavaScript sources | script-src 'self' https://cdn.example.com | | style-src | CSS sources | style-src 'self' 'unsafe-inline' | | img-src | Image sources | img-src 'self' data: | | connect-src | XMLHttpRequest, fetch, WebSocket | connect-src 'self' | | frame-ancestors | Parent page framing | frame-ancestors 'none' | | form-action | Form submission targets | form-action 'self' | | base-uri | `tag URLs |base-uri 'self'` |

Nonce and Hash Strategies

Using 'unsafe-inline' for scripts weakens CSP. Nonce and hash strategies provide secure inline script handling.

Nonce-Based CSP

A nonce is a cryptographically random token generated per-request and included in both the CSP header and the script tag.

import secrets

from flask import Flask, render_template

app = Flask(name)

@app.route('/')

def index():

nonce = secrets.token_urlsafe(16)

response = make_response(render_template('index.html', nonce=nonce))

response.headers['Content-Security-Policy'] = \

f"script-src 'nonce-{nonce}'; object-src 'none'; base-uri 'self'"


Read the full article on AI Study Room for complete code examples, comparison tables, and related resources.

Found this useful? Check out more developer guides and tool comparisons on AI Study Room.

Top comments (0)