Django: Basic Auth for one view (avoid middleware)

前端 未结 4 1148
星月不相逢
星月不相逢 2021-02-18 23:46

I need to provide http-basic-auth to one view.

I want to avoid modifying the middleware settings.

Background: This is a view which gets fil

4条回答
  •  我在风中等你
    2021-02-19 00:14

    For those that already use django-rest-framework (DRF):

    DRF has a BasicAuthentication class which, more-or-less, does what is described in the other answers (see source).

    This class can also be used in "normal" Django views.

    For example:

    from rest_framework.authentication import BasicAuthentication
    
    def my_view(request):
        # use django-rest-framework's basic authentication to get user
        user = None
        user_auth_tuple = BasicAuthentication().authenticate(request)
        if user_auth_tuple is not None:
            user, _ = user_auth_tuple
    

提交回复
热议问题