Home > Article > Web Front-end > How does Content Security Policy (CSP) protect websites from malicious code injections?
Often encountered errors in the developer console, such as "Refused to...", are a consequence of Content Security Policy (CSP), a security measure that restricts the loading of resources from untrusted sources.
CSP enables you to control where resources can be loaded from. You define allowed sources through directives in the HTTP header Content-Security-Policy. By setting these restrictions, you minimize the risk of malicious code injections like XSS attacks.
Common directives include:
1. Allow Multiple Sources:
content="default-src 'self' https://example.com/js/"
2. Define Multiple Directives:
content="default-src 'self' https://example.com/js/; style-src 'self'"
3. Handling Ports:
content="default-src 'self' https://example.com:123/free/stuff/"
4. Handling Different Protocols:
content="default-src 'self'; connect-src ws:; style-src 'self'"
5. Allowing File Protocol:
content="default-src filesystem"
6. Inline Styles and Scripts:
content="script-src 'unsafe-inline'; style-src 'unsafe-inline'"
7. Allowing eval():
content="script-src 'unsafe-eval'"
8. Meaning of 'self':
'self' refers to sources with the same scheme, host, and port as the file where the policy is defined.
9. Wildcard Warning:
While tempting, using content="default-src *" allows certain risky actions like allowing inline scripts and eval(). For true vulnerability, consider:
content="default-src * 'unsafe-inline' 'unsafe-eval'"
The above is the detailed content of How does Content Security Policy (CSP) protect websites from malicious code injections?. For more information, please follow other related articles on the PHP Chinese website!