temy13さんの記事 を参考に少し直したもの。
- python3 で decodestring が使えないと言われたのを修正
- Userデータベースと authenticate メソッドを使ってコードを改善
- 変数の名前をちょっとわかりやすくした
import base64
from django.contrib.auth import authenticate
.....
def _http401():
response = HttpResponse("Unauthorized", status=401)
response['WWW-Authenticate'] = 'Basic realm="basic auth username/password inalid"'
return response
def _basicAuth(request):
"""
:param request:
:return: True is authenticated. Otherwise return False
"""
if 'HTTP_AUTHORIZATION' not in request.META:
return False
(auth_scheme, base64_username_pass) = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
if auth_scheme.lower() != 'basic':
return _http401()
username_pass = base64.decodebytes(base64_username_pass.strip().encode('ascii')).decode('ascii')
(username, password) = username_pass.split(':', 1)
user = authenticate(username=username, password=password)
return user is not None
def sample_view_usage(request):
if not _basicAuth(request):
return _http401()
...