2
2

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 5 years have passed since last update.

Django basic auth

Posted at

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()
    ... 
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?