---
title: "flask-talisman | pypx"
description: "HTTP security headers for Flask."
canonical_url: "https://pypx.app/packages/flask-talisman"
meta:
  "og:description": "HTTP security headers for Flask."
  "og:image": "https://pypx.app/_og/d/h_630%2Cc_PackageCard%2Cname_flask-talisman%2Cversion_1.1.0%2Csummary_HTTP%2Bsecurity%2Bheaders%2Bfor%2BFlask.%2Clicense_Apache%2BSoftware%2BLicense%2Cp_Ii9wYWNrYWdlcy9mbGFzay10YWxpc21hbiI%2Cs_DUCmWZim3h9uZPMf.png"
  "og:image:height": "630"
  "og:image:type": image/png
  "og:image:width": "1200"
  "og:title": "flask-talisman 1.1.0"
  "twitter:image": "https://pypx.app/_og/d/h_630%2Cc_PackageCard%2Cname_flask-talisman%2Cversion_1.1.0%2Csummary_HTTP%2Bsecurity%2Bheaders%2Bfor%2BFlask.%2Clicense_Apache%2BSoftware%2BLicense%2Cp_Ii9wYWNrYWdlcy9mbGFzay10YWxpc21hbiI%2Cs_DUCmWZim3h9uZPMf.png"
---

> Index of every page on this site: [llms.txt](https://pypx.app/llms.txt)

# **flask-talisman**

v1.1.0

HTTP security headers for Flask.

19 KBpy2.py3-none-anyApache Software License Likely Unmaintained

[** Diff **](https://pypx.app/packages/flask-talisman/diff)

`$ uv add flask-talisman`

# Talisman: HTTP security headers for Flask

Talisman is a small Flask extension that handles setting HTTP headers that can help protect against a few common web application security issues.

The default configuration:

- Forces all connects to https, unless running with debug enabled.
- Enables \`HTTP Strict Transport

Security \<https://developer.mozilla.org/en-US/docs/Web/Security/HTTP\_strict\_transport\_security>\`\_.

- Sets Flask's session cookie to secure, so it will never be set if

your application is somehow accessed via a non-secure connection.

- Sets Flask's session cookie to httponly, preventing JavaScript

from being able to access its content. CSRF via Ajax uses a separate cookie and should be unaffected.

- Sets Flask's session cookie to Lax, preventing the cookie to be leaked

in CSRF-prone request methods.

- Sets

[X-Frame-Options](https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options) to SAMEORIGIN to avoid [clickjacking](https://en.wikipedia.org/wiki/Clickjacking).

- Sets \`X-Content-Type-Options

\<https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options>\`\_ to prevent content type sniffing.

- Sets a strict \`Content Security

Policy \<https://developer.mozilla.org/en-US/docs/Web/Security/CSP/Introducing\_Content\_Security\_Policy>`__ of` `default-src: 'self', 'object-src': 'none'``. This is intended to almost completely prevent Cross Site Scripting (XSS) attacks. This is probably the only setting that you should reasonably change. See the` Content Security Policy\`\_ section.

- Sets a strict [Referrer-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy)

of strict-origin-when-cross-origin that governs which referrer information should be included with requests made.

- Disables browsing-topics by default in the [Permissions-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy)

like [Drupal](https://www.drupal.org/project/drupal/issues/3209628) to enhance privacy protection.

In addition to Talisman, you **should always use a cross-site request forgery (CSRF) library**. It's highly recommended to use [Flask-SeaSurf](https://flask-seasurf.readthedocs.org/en/latest/), which is based on Django's excellent library.

## Installation & Basic Usage

Install via [pip](https://pypi.python.org/pypi/pip):

```
pip install flask-talisman
```

After installing, wrap your Flask app with a Talisman:

```python
from flask import Flask
from flask_talisman import Talisman

app = Flask(__name__)
Talisman(app)
```

There is also a full [Example App](https://github.com/wntrblm/flask-talisman/blob/master/example_app).

## Options

- force\_https, default True, forces all non-debug connects to

https ([about HTTPS](https://developer.mozilla.org/en-US/docs/Glossary/https)).

- force\_https\_permanent, default False, uses 301 instead of

302 for https redirects.

- frame\_options, default SAMEORIGIN, can be SAMEORIGIN,

DENY, or ALLOWFROM ([about Frame Options](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options)).

- frame\_options\_allow\_from, default None, a string indicating

the domains that are allowed to embed the site via iframe.

- strict\_transport\_security, default True, whether to send HSTS

headers ([about HSTS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security)).

- strict\_transport\_security\_preload, default False, enables HSTS

preloading. If you register your application with [Google's HSTS preload list](https://hstspreload.appspot.com/), Firefox and Chrome will never load your site over a non-secure connection.

- strict\_transport\_security\_max\_age, default ONE\_YEAR\_IN\_SECS,

length of time the browser will respect the HSTS header.

- strict\_transport\_security\_include\_subdomains, default True,

whether subdomains should also use HSTS.

- content\_security\_policy, default default-src: 'self' `, 'object-src': 'none'`\`, see the

`Content Security Policy`\_ section ([about Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy)).

- content\_security\_policy\_nonce\_in, default \[]. Adds a per-request nonce

value to the flask request object and also to the specified CSP header section. I.e. \['script-src', 'style-src']

- content\_security\_policy\_report\_only, default False, whether to set

the CSP header as "report-only" (as `Content-Security-Policy-Report-Only`) to ease deployment by disabling the policy enforcement by the browser, requires passing a value with the content\_security\_policy\_report\_uri parameter

- content\_security\_policy\_report\_uri, default None, a string

indicating the report URI used for [CSP violation reports](https://developer.mozilla.org/en-US/docs/Web/Security/CSP/Using_CSP_violation_reports)

- referrer\_policy, default strict-origin-when-cross-origin, a string

that sets the Referrer Policy header to send a full URL when performing a same-origin request, only send the origin of the document to an equally secure destination (HTTPS->HTTPS), and send no header to a less secure destination (HTTPS->HTTP) ([about Referrer Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy)).

- feature\_policy, default {}, see the `Feature Policy`\_ section ([about Feature Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Feature_Policy)).

- permissions\_policy, default {'browsing-topics': '()'}, see the `Permissions Policy`\_ section ([about Permissions Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Feature_Policy)).
- document\_policy, default {}, see the `Document Policy`\_ section ([about Document Policy](https://wicg.github.io/document-policy/)).

- session\_cookie\_secure, default True, set the session cookie

to secure, preventing it from being sent over plain http (`about cookies (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie)_`).

- session\_cookie\_http\_only, default True, set the session

cookie to httponly, preventing it from being read by JavaScript.

- session\_cookie\_samesite, default Lax, set this to Strict to prevent the cookie from being sent by the browser to the target site in all cross-site browsing context, even when following a regular link.

- force\_file\_save, default False, whether to set the

[X-Download-Options](<https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/compatibility/jj542450(v=vs.85)?redirectedfrom=MSDN>) header to noopen to prevent IE >= 8 to from opening file downloads directly and only save them instead.

- x\_content\_type\_options, default True, Protects against MIME sniffing vulnerabilities ([about Content Type Options](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options)).
- x\_xss\_protection, default False, Protects against cross-site scripting (XSS) attacks ([about XSS Protection](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection)). This option is disabled by default because no modern browser ([supports this header](https://caniuse.com/mdn-http_headers_x-xss-protection)) anymore.

For a full list of (security) headers, check out: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers.

### Per-view options

Sometimes you want to change the policy for a specific view. The force\_https, frame\_options, frame\_options\_allow\_from, `content_security_policy``,` `feature_policy``,` `permissions_policy`` and` `document_policy`\` options can be changed on a per-view basis.

```python
from flask import Flask
from flask_talisman import Talisman, ALLOW_FROM

app = Flask(__name__)
talisman = Talisman(app)

@app.route('/normal')
def normal():
    return 'Normal'

@app.route('/embeddable')
@talisman(frame_options=ALLOW_FROM, frame_options_allow_from='*')
def embeddable():
    return 'Embeddable'
```

## Content Security Policy

The default content security policy is extremely strict and will prevent loading any resources that are not in the same domain as the application. Most web applications will need to change this policy. If you're not ready to deploy Content Security Policy, you can set `content_security_policy` to `False` to disable sending this header entirely.

A slightly more permissive policy is available at flask\_talisman.GOOGLE\_CSP\_POLICY, which allows loading Google-hosted JS libraries, fonts, and embeding media from YouTube and Maps.

You can and should create your own policy to suit your site's needs. Here's a few examples adapted from [MDN](https://developer.mozilla.org/en-US/docs/Web/Security/CSP/Using_Content_Security_Policy):

### Example 1

This is the default policy. A web site administrator wants all content to come from the site's own origin (this excludes subdomains) and disallow legacy HTML elements.

```python
csp = {
    'default-src': '\'self\'',
    'object-src': '\'none\'',
}
talisman = Talisman(app, content_security_policy=csp)
```

### Example 2

A web site administrator wants to allow content from a trusted domain and all its subdomains (it doesn't have to be the same domain that the CSP is set on.)

```python
csp = {
    'default-src': [
        '\'self\'',
        '*.trusted.com'
    ]
}
```

### Example 3

A web site administrator wants to allow users of a web application to include images from any origin in their own content, but to restrict audio or video media to trusted providers, and all scripts only to a specific server that hosts trusted code.

```python
csp = {
    'default-src': '\'self\'',
    'img-src': '*',
    'media-src': [
        'media1.com',
        'media2.com',
    ],
    'script-src': 'userscripts.example.com'
}
```

In this example content is only permitted from the document's origin with the following exceptions:

- Images may loaded from anywhere (note the \* wildcard).
- Media is only allowed from media1.com and media2.com (and not from

subdomains of those sites).

- Executable script is only allowed from userscripts.example.com.

### Example 4

A web site administrator for an online banking site wants to ensure that all its content is loaded using SSL, in order to prevent attackers from eavesdropping on requests.

```python
csp = {
    'default-src': 'https://onlinebanking.jumbobank.com'
}
```

The server only permits access to documents being loaded specifically over HTTPS through the single origin onlinebanking.jumbobank.com.

### Example 5

A web site administrator of a web mail site wants to allow HTML in email, as well as images loaded from anywhere, but not JavaScript or other potentially dangerous content.

```python
csp = {
    'default-src': [
        '\'self\'',
        '*.mailsite.com',
    ],
    'img-src': '*'
}
```

Note that this example doesn't specify a script-src; with the example CSP, this site uses the setting specified by the default-src directive, which means that scripts can be loaded only from the originating server.

### Example 6

A web site administrator wants to allow embedded scripts (which might be generated dynamicially).

```python
csp = {
    'default-src': '\'self\'',
    'script-src': '\'self\'',
}
talisman = Talisman(
    app,
    content_security_policy=csp,
    content_security_policy_nonce_in=['script-src']
)
```

The nonce needs to be added to the script tag in the template:

```html
<script nonce="{{ csp_nonce() }}">
    //...
</script>
```

Note that the CSP directive (`script-src` in the example) to which the `nonce-...` source should be added needs to be defined explicitly.

### Example 7

A web site adminstrator wants to override the CSP directives via an environment variable which doesn't support specifying the policy as a Python dictionary, e.g.:

```bash
export CSP_DIRECTIVES="default-src 'self'; image-src *"
python app.py
```

Then in the app code you can read the CSP directives from the environment:

```python
import os
from flask_talisman import Talisman, DEFAULT_CSP_POLICY

talisman = Talisman(
    app,
    content_security_policy=os.environ.get("CSP_DIRECTIVES", DEFAULT_CSP_POLICY),
)
```

As you can see above the policy can be defined simply just like the official specification requires the HTTP header to be set: As a semicolon separated list of individual CSP directives.

## Feature Policy

**Note:** Feature Policy has largely been [renamed Permissions Policy](https://github.com/w3c/webappsec-feature-policy/issues/359) in the latest draft and some features are likely to move to Document Policy. At this writing, most browsers support the Feature-Policy HTTP Header name. See the `Permissions Policy`\_ and `Document Policy`\_ sections below should you wish to set these.

Also note that the Feature Policy specification did not progress beyond the `draft https://wicg.github.io/feature-policy/` stage before being renamed, but is [supported in some form in most browsers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy#Browser_compatibility).

The default feature policy is empty, as this is the default expected behaviour.

### Geolocation Example

Disable access to Geolocation interface.

```python
feature_policy = {
    'geolocation': '\'none\''
}
talisman = Talisman(app, feature_policy=feature_policy)
```

## Permissions Policy

Feature Policy has been split into Permissions Policy and Document Policy but at this writing [browser support of Permissions Policy is very limited](https://caniuse.com/permissions-policy), and it is recommended to still set the Feature-Policy HTTP Header. Permission Policy support is included in Talisman for when this becomes more widely supported.

Note that the [Permission Policy is still an Working Draft](https://www.w3.org/TR/permissions-policy/).

When the same feature or permission is set in both Feature Policy and Permission Policy, the Permission Policy setting will take precedence in browsers that support both.

It should be noted that the syntax differs between Feature Policy and Permission Policy as can be seen from the geolocation examples provided.

The default Permissions Policy is browsing-topics=(), which opts sites out of [Federated Learning of Cohorts](https://wicg.github.io/floc/) an interest-based advertising initiative called Topics API.

Permission Policy can be set either using a dictionary, or using a string.

### Geolocation and Microphone Example

Disable access to Geolocation interface and Microphone using dictionary syntax

```python
permissions_policy = {
    'geolocation': '()',
    'microphone': '()'
}
talisman = Talisman(app, permissions_policy=permissions_policy)
```

Disable access to Geolocation interface and Microphone using string syntax

```python
permissions_policy = 'geolocation=(), microphone=()'
talisman = Talisman(app, permissions_policy=permissions_policy)
```

## Document Policy

Feature Policy has been split into Permissions Policy and Document Policy but at this writing [browser support of Document Policy is very limited](https://caniuse.com/document-policy), and it is recommended to still set the Feature-Policy HTTP Header. Document Policy support is included in Talisman for when this becomes more widely supported.

Note that the [Document Policy is still an Unofficial Draft](https://wicg.github.io/document-policy/).

The default Document Policy is empty, as this is the default expected behaviour.

Document Policy can be set either using a dictionary, or using a string.

### Oversized-Images Example

Forbid oversized-images using dictionary syntax:

```python
document_policy = {
    'oversized-images': '?0'
}
talisman = Talisman(app, document_policy=document_policy)
```

Forbid oversized-images using string syntax:

```python
document_policy = 'oversized-images=?0'
talisman = Talisman(app, document_policy=document_policy)
```

## Disclaimer

This code originated at Google, but is not an official Google product, experimental or otherwise. It was forked on June 6th, 2021 from the unmaintained GoogleCloudPlatform/flask-talisman.

There is no silver bullet for web application security. Talisman can help, but security is more than just setting a few headers. Any public-facing web application should have a comprehensive approach to security.

## Contributing changes

- See `CONTRIBUTING.md`\_

## Licensing

- Apache 2.0 - See `LICENSE`\_

## **Details **

<dl>

<dt>Version</dt>
<dd>1.1.0</dd>

<dt>License</dt>
<dd>Apache Software License</dd>

<dt>Maintainer</dt>
<dd>Alethea Katherine Flowers</dd></dl>

## **Links**

- [Homepage](https://github.com/wntrblm/flask-talisman)
- [View on PyPI](https://pypi.org/project/flask-talisman/)

## **Maintainers **

- Alethea Katherine Flowers · [me@thea.codes](mailto:me@thea.codes)

```json
{"@context":"https://schema.org","@graph":[{"@id":"https://pypx.app/#website","@type":"WebSite","description":"The Python Package Index, reimagined. Fast search, dependency insights, download trends, and changelogs — all in one place.","name":"pypx","url":"https://pypx.app/"},{"@id":"https://pypx.app/packages/flask-talisman#webpage","@type":"WebPage","description":"HTTP security headers for Flask.","name":"flask-talisman","url":"https://pypx.app/packages/flask-talisman","isPartOf":{"@id":"https://pypx.app/#website"},"potentialAction":[{"@type":"ReadAction","target":["https://pypx.app/packages/flask-talisman"]}]},{"@id":"https://pypx.app/packages/flask-talisman#/schema/software-application/1","@type":"SoftwareApplication","applicationCategory":"DeveloperApplication","description":"HTTP security headers for Flask.","license":"Apache Software License","name":"flask-talisman","softwareVersion":"1.1.0"}]}
```

## Sitemap

See the full [sitemap](https://pypx.app/sitemap.md) for all pages.
