Django:一个视图的基本Auth(避免中间件)

时间:2022-11-11 07:18:35

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

我需要为一个视图提供http-basic-auth。

I want to avoid modifying the middleware settings.

我想避免修改中间件设置。

Background: This is a view which gets filled in by a remote application.

背景:这是一个由远程应用程序填充的视图。

3 个解决方案

#1


9  

When you do a basic auth request, you're really adding credentials into the Authorization header. Before transit, these credentials are base64-encoded, so you need to decode them on receipt.

当您执行基本的auth请求时,您实际上是在授权头中添加凭据。在传输之前,这些凭据是base64编码的,因此需要在接收时对它们进行解码。

The following code snippet presumes that there's only one valid username and password:

下面的代码片段假设只有一个有效的用户名和密码:

import base64

def my_view(request):
    auth_header = request.META.get('HTTP_AUTHORIZATION', '')
    token_type, _, credentials = auth_header.partition(' ')

    expected = base64.b64encode(b'username:password').decode()

    if token_type != 'Basic' or credentials != expected:
        return HttpResponse(status=401)

    # Your authenticated code here:
    ...

If you wish to compare to the username and password of a User model, try the following instead:

如果您希望比较用户模型的用户名和密码,请尝试以下方法:

def my_view(request):
    auth_header = request.META.get('HTTP_AUTHORIZATION', '')
    token_type, _, credentials = auth_header.partition(' ')

    username, password = base64.b64decode(credentials).split(':')
    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        return HttpResponse(status=401)

    password_valid = user.check_password(password)

    if token_type != 'Basic' or not password_valid:
        return HttpResponse(status=401)

    # Your authenticated code here:
    ...

Please note that this latter version is not extremely secure. At first glance, I can see that it is vulnerable to timing attacks, for example.

请注意,后一个版本不是非常安全。乍一看,我可以看到它很容易受到定时攻击,例如。

#2


4  

This library could be used: https://github.com/hirokiky/django-basicauth

这个库可以使用:https://github.com/hirokiky/django-basicauth

Basic auth utilities for Django.

Django的基本auth实用程序。

The docs show how to use it:

文档展示了如何使用它:

Applying decorator to CBVs

将修饰符应用于CBVs

To apply @basic_auth_requried decorator to Class Based Views, use django.utils.decorators.method_decorator.

要将@basic_auth_requried decorator应用到基于类的视图,请使用django.utils.decorators.decorators.method_decorator。

Source: https://github.com/hirokiky/django-basicauth#applying-decorator-to-cbvs

来源:https://github.com/hirokiky/django-basicauth applying-decorator-to-cbvs

#3


0  

You can try a custom decorator (as seems to be the recommended way here and here) instead of adding new middleware:

您可以尝试自定义decorator(这里和这里似乎是推荐的方式),而不是添加新的中间件:

my_app/decorators.py:

my_app / decorators.py:

import base64

from django.http import HttpResponse
from django.contrib.auth import authenticate
from django.conf import settings


def basicauth(function):
    def wrap(request, *args, **kwargs):
        if 'HTTP_AUTHORIZATION' in request.META:
            auth = request.META['HTTP_AUTHORIZATION'].split()
            if len(auth) == 2:
                if auth[0].lower() == "basic":
                    uname, passwd = base64.b64decode(auth[1]).split(':')
                    user = authenticate(username=uname, password=passwd)
                    if user is not None and user.is_active:
                        request.user = user
                        return view(request, *args, **kwargs)

        response = HttpResponse()
        response.status_code = 401
        response['WWW-Authenticate'] = 'Basic realm="{}"'.format(
            settings.BASIC_AUTH_REALM
        )
        return response

Then use this to decorate your view:

然后用这个来装饰你的视图:

from my_app.decorators import basicauth


@basicauth
def my_view(request):
    ...

#1


9  

When you do a basic auth request, you're really adding credentials into the Authorization header. Before transit, these credentials are base64-encoded, so you need to decode them on receipt.

当您执行基本的auth请求时,您实际上是在授权头中添加凭据。在传输之前,这些凭据是base64编码的,因此需要在接收时对它们进行解码。

The following code snippet presumes that there's only one valid username and password:

下面的代码片段假设只有一个有效的用户名和密码:

import base64

def my_view(request):
    auth_header = request.META.get('HTTP_AUTHORIZATION', '')
    token_type, _, credentials = auth_header.partition(' ')

    expected = base64.b64encode(b'username:password').decode()

    if token_type != 'Basic' or credentials != expected:
        return HttpResponse(status=401)

    # Your authenticated code here:
    ...

If you wish to compare to the username and password of a User model, try the following instead:

如果您希望比较用户模型的用户名和密码,请尝试以下方法:

def my_view(request):
    auth_header = request.META.get('HTTP_AUTHORIZATION', '')
    token_type, _, credentials = auth_header.partition(' ')

    username, password = base64.b64decode(credentials).split(':')
    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        return HttpResponse(status=401)

    password_valid = user.check_password(password)

    if token_type != 'Basic' or not password_valid:
        return HttpResponse(status=401)

    # Your authenticated code here:
    ...

Please note that this latter version is not extremely secure. At first glance, I can see that it is vulnerable to timing attacks, for example.

请注意,后一个版本不是非常安全。乍一看,我可以看到它很容易受到定时攻击,例如。

#2


4  

This library could be used: https://github.com/hirokiky/django-basicauth

这个库可以使用:https://github.com/hirokiky/django-basicauth

Basic auth utilities for Django.

Django的基本auth实用程序。

The docs show how to use it:

文档展示了如何使用它:

Applying decorator to CBVs

将修饰符应用于CBVs

To apply @basic_auth_requried decorator to Class Based Views, use django.utils.decorators.method_decorator.

要将@basic_auth_requried decorator应用到基于类的视图,请使用django.utils.decorators.decorators.method_decorator。

Source: https://github.com/hirokiky/django-basicauth#applying-decorator-to-cbvs

来源:https://github.com/hirokiky/django-basicauth applying-decorator-to-cbvs

#3


0  

You can try a custom decorator (as seems to be the recommended way here and here) instead of adding new middleware:

您可以尝试自定义decorator(这里和这里似乎是推荐的方式),而不是添加新的中间件:

my_app/decorators.py:

my_app / decorators.py:

import base64

from django.http import HttpResponse
from django.contrib.auth import authenticate
from django.conf import settings


def basicauth(function):
    def wrap(request, *args, **kwargs):
        if 'HTTP_AUTHORIZATION' in request.META:
            auth = request.META['HTTP_AUTHORIZATION'].split()
            if len(auth) == 2:
                if auth[0].lower() == "basic":
                    uname, passwd = base64.b64decode(auth[1]).split(':')
                    user = authenticate(username=uname, password=passwd)
                    if user is not None and user.is_active:
                        request.user = user
                        return view(request, *args, **kwargs)

        response = HttpResponse()
        response.status_code = 401
        response['WWW-Authenticate'] = 'Basic realm="{}"'.format(
            settings.BASIC_AUTH_REALM
        )
        return response

Then use this to decorate your view:

然后用这个来装饰你的视图:

from my_app.decorators import basicauth


@basicauth
def my_view(request):
    ...