0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

flaskでCSP(Content Security Policy)をflask-talismanで実装する方法

Last updated at Posted at 2023-02-19

flaskで、簡単にcspの設定をできたので、以下に備忘録として書き記す。

flask-talisman

flaskのドキュメントでflask-talismanを紹介していたので、flask-talismanでCSPの設定を行っていく。

CSPの設定方法

flaskとflask-talismanのインストール

pip install flask
pip install flask-talisman

以下、pythonファイル

from flask import Flask
from flask_talisman import Talisman, ALLOW_FROM


app = Flask(__name__)

csp = {
    'default-src': [
        '\'self\'',
        #以下に読み込む必要のあるドメインを書いていく
        '*.qiita.com'
    ]
}
talisman = Talisman(app, content_security_policy=csp)


@app.route('/')
#CSPの設定を適用するところに以下のデコレータを設置
@talisman(frame_options=ALLOW_FROM, frame_options_allow_from='*')
def index():
    return '<h1>Hello World!</h1>'

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=10000)

実行結果

以下、PythonAnyWhereでHostingしたものをスクショした画像
画像1.png
この記事のコードで作成したflaskのサイト
https://hellouniverse4.pythonanywhere.com/

あとがき

flaskでCSPの設定を行う方法を紹介した。筆者自身、思っていたよりも簡単に実装できて驚いている。今後もflaskライフを楽しんでいこうと思う。

参考記事

https://github.com/GoogleCloudPlatform/flask-talisman
https://msiz07-flask-docs-ja.readthedocs.io/ja/latest/security.html

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?