LoginSignup
15
13

More than 3 years have passed since last update.

[Django]特定の環境下でBasic認証をかけたいときは

Last updated at Posted at 2019-07-24

やりたいこと

公開前のWebアプリなどでBasic認証をかけたい場合があるかもしれません。
PHPなんかだと .htaccess .htpasswd でシュッとやれるのですが、Djangoだとうまくできなかったので備忘録を兼ねて。

導入

wsgi-basic-auth というライブラリがあったので入れました。

インストール

pip install wsgi-basic-auth
.env
+ WSGI_AUTH_CREDENTIALS=id:password

ここの idpassword を好きに書き換えてください。

[project]/wsgi.py
from wsgi_basic_auth import BasicAuth
application = BasicAuth(application)

結果

スクリーンショット 2019-07-24 19.50.39.png

こんな感じで簡単にBasic認証がかけられます。

特定の環境のみBasic認証をかけたい場合

django-environ を使用しました。

.env
+ APP_ENV=development
[project]/wsgi.py
import environ
env = environ.Env()
env.read_env('.env')

if env('APP_ENV') == 'development' :
    from wsgi_basic_auth import BasicAuth
    application = BasicAuth(application)
15
13
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
15
13