contentSecurityPolicy function

Middleware contentSecurityPolicy({
  1. ContentSecurityPolicyOptions options = const ContentSecurityPolicyOptions.useDefaults(),
})

Content Security Policy (CSP) helps prevent unwanted content from being injected/loaded into your webpages. This can mitigate cross-site scripting (XSS) vulnerabilities, clickjacking, formjacking, malicious frames, unwanted trackers, and other web client-side attacks. If you want to learn how CSP works, check out the fantastic HTML5 Rocks guide, the Content Security Policy Reference, and the Content Security Policy specification.

This middleware helps set Content Security Policies.

Basic usage:

import 'package:shelf_helmet/shelf_helmet.dart'

.addMiddleware(
  contentSecurityPolicy(
    options: const ContentSecurityPolicyOptions.useDefaults(
      useDefaults: true,
      directives: {
        defaultSrc: ["'self'", "default.example"],
        scriptSrc: ["'self'", "js.example.com"],
        objectSrc: ["'none'"],
        upgradeInsecureRequests: [],
      },
      reportOnly: false,
    ),
  ),
);

If no directives are supplied, the following policy is set (whitespace added for readability):

default-src 'self';
base-uri 'self';
font-src 'self' https: data:;
form-action 'self';
frame-ancestors 'self';
img-src 'self' data:;
object-src 'none';
script-src 'self';
script-src-attr 'none';
style-src 'self' https: 'unsafe-inline';
upgrade-insecure-requests

You can use this default with the ContentSecurityPolicyOptions.useDefaults() constructor or set the bool to true. useDefaults is true by default.

You can also get the default directives object with ContentSecurityPolicy.getDefaultDirectives.

You can set any directives you wish. defaultSrc is required, but can be explicitly disabled by using the ContentSecurityPolicyOptions.dangerouslyDisableDefaultSrc() constructor. Directives can be kebab-cased (like script-src) or camel-cased (like scriptSrc). They are equivalent, but duplicates are not allowed.

The reportOnly option, if set to true, sets the Content-Security-Policy-Report-Only header instead. If you want to set both the normal and Report-Only headers, you can do this like described here:

.addMiddleware(
  contentSecurityPolicy(
    options: const ContentSecurityPolicyOptions.useDefaults(
      useDefaults: true,
      reportOnly: false,
    ),
  ),
);
.addMiddleware(
  contentSecurityPolicy(
    options: const ContentSecurityPolicyOptions.useDefaults(
      useDefaults: true,
      reportOnly: true,
    ),
  ),
);

This middleware does minimal validation. You should use a more sophisticated CSP validator, like Google's CSP Evaluator, to make sure your CSP looks good.

See also

Implementation

Middleware contentSecurityPolicy({
  ContentSecurityPolicyOptions options =
      const ContentSecurityPolicyOptions.useDefaults(),
}) {
  return (innerHandler) {
    return (request) async {
      final response = await innerHandler(request);
      return response.change(
        headers: {
          options.reportOnly
                  ? 'Content-Security-Policy-Report-Only'
                  : 'Content-Security-Policy':
              getHeaderValue(_normalizeDirectives(options)),
        },
      );
    };
  };
}