Class ContentSecurityPolicy
Content Security Policy is a security standard that helps prevent cross-site scripting (XSS), clickjacking, and other code injection attacks by specifying which content sources are allowed to be loaded by the browser. This class provides a type-safe, discoverable API for building CSP directives without manually constructing raw header strings.
Usage:
ContentSecurityPolicy csp = new ContentSecurityPolicy();
csp.addDefaultSrc(ContentSecurityPolicy.SELF);
csp.addScriptSrc(ContentSecurityPolicy.SELF, "https://cdn.example.com");
csp.addStyleSrc(ContentSecurityPolicy.SELF, ContentSecurityPolicy.UNSAFE_INLINE);
csp.addImgSrc(ContentSecurityPolicy.SELF, "data:", "https:");
csp.upgradeInsecureRequests();
// Use with Head element
head.setContentSecurityPolicy(csp);
// Or get the raw header value
String headerValue = csp.toString();
// "default-src 'self'; script-src 'self' https://cdn.example.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; upgrade-insecure-requests"
- Since:
- 2.0
- Version:
- 1.0
- Author:
- Marvin P. Warble Jr.
-
Field Summary
Fields -
Constructor Summary
ConstructorsConstructorDescriptionCreates a new empty Content Security Policy builder. -
Method Summary
Modifier and TypeMethodDescriptionaddBaseUri(String... sources) Adds sources to thebase-uridirective.addChildSrc(String... sources) Adds sources to thechild-srcdirective.addConnectSrc(String... sources) Adds sources to theconnect-srcdirective.addDefaultSrc(String... sources) Adds sources to thedefault-srcdirective.addDirective(String directive, String... sources) Adds sources to a custom or future directive.addFontSrc(String... sources) Adds sources to thefont-srcdirective.addFormAction(String... sources) Adds sources to theform-actiondirective.addFrameAncestors(String... sources) Adds sources to theframe-ancestorsdirective.addFrameSrc(String... sources) Adds sources to theframe-srcdirective.Adds sources to theimg-srcdirective.addManifestSrc(String... sources) Adds sources to themanifest-srcdirective.addMediaSrc(String... sources) Adds sources to themedia-srcdirective.addObjectSrc(String... sources) Adds sources to theobject-srcdirective.addSandbox(String... flags) Adds flags to thesandboxdirective.addScriptSrc(String... sources) Adds sources to thescript-srcdirective.addStyleSrc(String... sources) Adds sources to thestyle-srcdirective.addWorkerSrc(String... sources) Adds sources to theworker-srcdirective.static StringReturns a nonce source expression for use in CSP directives.setReportTo(String groupName) Sets thereport-todirective.setReportUri(String uri) Sets thereport-uridirective.static StringReturns a SHA-256 hash source expression for use in CSP directives.static StringReturns a SHA-384 hash source expression for use in CSP directives.static StringReturns a SHA-512 hash source expression for use in CSP directives.toString()Returns the Content Security Policy as a formatted header value string.Enables theupgrade-insecure-requestsdirective.
-
Field Details
-
SELF
- See Also:
-
NONE
- See Also:
-
UNSAFE_INLINE
- See Also:
-
UNSAFE_EVAL
- See Also:
-
STRICT_DYNAMIC
- See Also:
-
UNSAFE_HASHES
- See Also:
-
-
Constructor Details
-
ContentSecurityPolicy
public ContentSecurityPolicy()Creates a new empty Content Security Policy builder.
-
-
Method Details
-
addDefaultSrc
Adds sources to thedefault-srcdirective.The
default-srcdirective serves as a fallback for other fetch directives. If a specific directive is not defined, the browser falls back to the value ofdefault-src.- Parameters:
sources- one or more source expressions (e.g.,SELF, domain URLs)- Returns:
- this instance for method chaining
-
addScriptSrc
Adds sources to thescript-srcdirective.Controls which scripts the browser is allowed to execute. This is one of the most important directives for preventing XSS attacks.
- Parameters:
sources- one or more source expressions- Returns:
- this instance for method chaining
-
addStyleSrc
Adds sources to thestyle-srcdirective.Controls which stylesheets the browser is allowed to apply to the document.
- Parameters:
sources- one or more source expressions- Returns:
- this instance for method chaining
-
addImgSrc
Adds sources to theimg-srcdirective.Controls which image sources the browser is allowed to load.
- Parameters:
sources- one or more source expressions (e.g.,SELF, "data:", "https:")- Returns:
- this instance for method chaining
-
addFontSrc
Adds sources to thefont-srcdirective.Controls which font sources the browser is allowed to load.
- Parameters:
sources- one or more source expressions- Returns:
- this instance for method chaining
-
addConnectSrc
Adds sources to theconnect-srcdirective.Controls which URLs the browser is allowed to connect to via script interfaces such as XMLHttpRequest, WebSocket, fetch, and EventSource.
- Parameters:
sources- one or more source expressions- Returns:
- this instance for method chaining
-
addMediaSrc
Adds sources to themedia-srcdirective.Controls which media sources the browser is allowed to load for audio and video elements.
- Parameters:
sources- one or more source expressions- Returns:
- this instance for method chaining
-
addObjectSrc
Adds sources to theobject-srcdirective.Controls which plugin sources the browser is allowed to load for object, embed, and applet elements. Setting this to
NONEis recommended for security.- Parameters:
sources- one or more source expressions- Returns:
- this instance for method chaining
-
addFrameSrc
Adds sources to theframe-srcdirective.Controls which URLs the browser is allowed to load in frames and iframes.
- Parameters:
sources- one or more source expressions- Returns:
- this instance for method chaining
-
addChildSrc
Adds sources to thechild-srcdirective.Controls which URLs the browser is allowed to load for nested browsing contexts (frames) and worker execution contexts.
- Parameters:
sources- one or more source expressions- Returns:
- this instance for method chaining
-
addWorkerSrc
Adds sources to theworker-srcdirective.Controls which URLs the browser is allowed to load as Worker, SharedWorker, or ServiceWorker scripts.
- Parameters:
sources- one or more source expressions- Returns:
- this instance for method chaining
-
addManifestSrc
Adds sources to themanifest-srcdirective.Controls which URLs the browser is allowed to load as application manifests.
- Parameters:
sources- one or more source expressions- Returns:
- this instance for method chaining
-
addBaseUri
Adds sources to thebase-uridirective.Restricts the URLs that can be used in the document's
<base>element. Setting this toSELForNONEis recommended to prevent base tag injection attacks.- Parameters:
sources- one or more source expressions- Returns:
- this instance for method chaining
-
addFormAction
Adds sources to theform-actiondirective.Restricts which URLs can be used as the target of form submissions from the document.
- Parameters:
sources- one or more source expressions- Returns:
- this instance for method chaining
-
addFrameAncestors
Adds sources to theframe-ancestorsdirective.Specifies valid parents that may embed the page using
<frame>,<iframe>,<object>, or<embed>. Setting this toNONEis equivalent to theX-Frame-Options: DENYheader.- Parameters:
sources- one or more source expressions- Returns:
- this instance for method chaining
-
addSandbox
Adds flags to thesandboxdirective.Enables a sandbox for the document, similar to the
<iframe sandbox>attribute. Sandbox flags control which features are allowed, such as "allow-scripts", "allow-forms", "allow-popups", etc. Calling this method with no arguments applies the strictest sandbox restrictions.- Parameters:
flags- zero or more sandbox flags (e.g., "allow-scripts", "allow-forms")- Returns:
- this instance for method chaining
-
setReportUri
Sets thereport-uridirective.Specifies a URL to which the browser will send reports when the content security policy is violated. Note that
report-uriis deprecated in favor ofreport-to, but is still widely supported by browsers.- Parameters:
uri- the URI to receive CSP violation reports- Returns:
- this instance for method chaining
-
setReportTo
Sets thereport-todirective.Specifies a reporting group name (defined via the
Report-ToHTTP header) to which the browser will send CSP violation reports.- Parameters:
groupName- the reporting group name- Returns:
- this instance for method chaining
-
upgradeInsecureRequests
Enables theupgrade-insecure-requestsdirective.Instructs the browser to treat all of the site's insecure URLs (HTTP) as though they have been replaced with secure URLs (HTTPS). This is intended for websites with large numbers of insecure legacy URLs that need to be rewritten.
- Returns:
- this instance for method chaining
-
addDirective
Adds sources to a custom or future directive.This method provides an escape hatch for directives that are not covered by the typed methods, such as new or experimental directives. Calling this method multiple times for the same directive accumulates sources rather than replacing them.
- Parameters:
directive- the directive name (e.g., "prefetch-src")sources- one or more source expressions- Returns:
- this instance for method chaining
-
nonce
Returns a nonce source expression for use in CSP directives.A nonce is a randomly generated value that allows specific inline scripts or styles to execute. The same nonce must be present in both the CSP header and the script/style element's
nonceattribute.- Parameters:
value- the nonce value (should be a cryptographically random base64-encoded string)- Returns:
- the formatted nonce expression (e.g.,
'nonce-abc123')
-
sha256
Returns a SHA-256 hash source expression for use in CSP directives.Allows a specific inline script or style to execute by matching its SHA-256 hash. The hash should be the base64-encoded SHA-256 digest of the script or style content.
- Parameters:
hash- the base64-encoded SHA-256 hash- Returns:
- the formatted hash expression (e.g.,
'sha256-abc123...')
-
sha384
Returns a SHA-384 hash source expression for use in CSP directives.Allows a specific inline script or style to execute by matching its SHA-384 hash. The hash should be the base64-encoded SHA-384 digest of the script or style content.
- Parameters:
hash- the base64-encoded SHA-384 hash- Returns:
- the formatted hash expression (e.g.,
'sha384-abc123...')
-
sha512
Returns a SHA-512 hash source expression for use in CSP directives.Allows a specific inline script or style to execute by matching its SHA-512 hash. The hash should be the base64-encoded SHA-512 digest of the script or style content.
- Parameters:
hash- the base64-encoded SHA-512 hash- Returns:
- the formatted hash expression (e.g.,
'sha512-abc123...')
-
toString
Returns the Content Security Policy as a formatted header value string.Produces a semicolon-separated string of all configured directives, suitable for use as the value of a
Content-Security-PolicyHTTP header or thecontentattribute of a<meta http-equiv="content-security-policy">element.
-