【发布时间】:2010-12-08 21:09:31
【问题描述】:
我也有类似的问题 -
Conditional login redirect in Django
但我不明白如何从那里的答案中获得结果。
我对 django 比较陌生。我从某个地方重用了这段代码,它将用户重定向到登录页面。但是登录后我总是会进入用户的开始/主页。我希望他们看到他们真正请求的页面,而不是一直看到用户主页。你能告诉我我可以在哪里进行更改吗?应该是我使用“重定向”功能的地方。我可能应该保存一些会话变量并执行此操作,但还不是起点。有什么想法吗?
下面是代码-
def view_or_basicauth(view, request, test_func, realm = "", *args, **kwargs):
if test_func(request.user): # Already logged in, just return the view.
return view(request, *args, **kwargs)
# They are not logged in. See if they provided login credentials
if 'HTTP_AUTHORIZATION' in request.META:
auth = request.META['HTTP_AUTHORIZATION'].split()
if len(auth) == 2:
# NOTE: We are only support basic authentication for now.
if auth[0].lower() == "basic":
uname, passwd = base64.b64decode(auth[1]).split(':')
user = authenticate(username=uname, password=passwd)
if user is not None:
if user.is_active:
login(request, user)
request.user = user
return view(request, *args, **kwargs)
# Either they did not provide an authorization header or something in the authorization attempt failed. Send a 401 back to them to ask them to authenticate.
key = request.path.split('/')
if len(key) > 1:
base_url = request.get_host()
return redirect( 'https://' + base_url + '/login/')
s = '401 Unauthorized'
response = HttpResponse(s)
response.status_code = 401
response['Content-Length'] = '%d' % len(s)
response['WWW-Authenticate'] = 'Basic realm="%s"' % realm
return response
【问题讨论】:
-
您通常不应使用基本身份验证。除非通过 SSL 加密,否则凭据会在 每个 请求中以明文 传输。这对于大多数网站来说太脆弱了。
django.contrib.auth(docs.djangoproject.com/en/dev/topics/auth) 提供了一个非常适合广大用户的基于会话的解决方案,或者使用 django-openid (github.com/simonw/django-openid)
标签: python django url-routing redirect