我需要为一个视图提供http-basic-auth。
我希望避免修改中间件设置。
背景:这是一个由远程应用程序填充的视图。
发布于 2017-10-13 13:49:53
这个库可以使用:https://github.com/hirokiky/django-basicauth
Django的基本工具。
文档展示了如何使用它:
在CBV中应用装饰器 若要将@basic_auth_requried装饰器应用于基于类的视图,请使用django.utils.decorators.method_decorator。
来源:https://github.com/hirokiky/django-basicauth#applying-decorator-to-cbvs
发布于 2017-09-26 14:00:08
当您执行基本的auth请求时,实际上是在将凭据添加到Authorization头中。在传输之前,这些凭据是base64 64编码的,因此您需要在收到它们时对它们进行解码。
下面的代码片段假定只有一个有效的用户名和密码:
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:
...如果您希望与User模型的用户名和密码进行比较,请尝试以下操作:
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:
...请注意,后一个版本并不是非常安全。例如,乍一看,我可以看到它容易受到定时攻击的攻击。
发布于 2017-12-20 09:23:01
您可以尝试使用自定义装饰器(这似乎是推荐的这里和这里方式),而不是添加新的中间件:
my_app/decorators.py
import base64
from django.http import HttpResponse
from django.contrib.auth import authenticate
from django.conf import settings
def basicauth(view):
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]).decode(
"utf8"
).split(':', 1)
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
return wrap然后用这个来装饰你的观点:
from my_app.decorators import basicauth
@basicauth
def my_view(request):
...https://stackoverflow.com/questions/46426683
复制相似问题