我需要为一个 View 提供 http-basic-auth
。
我想避免修改中间件设置。
背景:这是一个由远程应用程序填充的 View 。
最佳答案
当您执行基本身份验证请求时,您实际上是在将凭据添加到 Authorization
header 中。在传输之前,这些凭据采用 base64 编码,因此您需要在收到时对其进行解码。
以下代码片段假定只有一个有效的用户名和密码:
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:
...
请注意,后一个版本不是非常安全。乍一看,我可以看出它容易受到 timing attacks 的攻击。 ,例如。
关于python - Django:一个 View 的基本身份验证(避免中间件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46426683/