django logout using a link or form to prevent csrf exploit

大兔子大兔子 提交于 2019-12-08 01:18:04

问题


while reading up djangobook chapter ,I came across the section which mentions a csrf exploit where a logout link was put in a hidden of malicious site.

In a web app I created using django,I had used a similar logout link

base.html:

<a  href="{% url my_logout %}" > Logout </a>

where the my_logout url points to django.contrib.auth.views.logout_then_login

urlpatterns=patterns('django.contrib.auth.views',
url(r'^logout/$', 'logout_then_login', {}, name = 'my_logout'),
)

Now,after reading about csrf attack,I fear that a malicious site can cause trouble for me too.So,I would like to use a form to do the logging out.

I thought I could do like this

base.html:

    ...

    <form method="post" action=".">{% csrf_token %}
        <input type="hidden" name="next" value="{{next}}" />
        <input type="hidden" name="confirm" value="true" />
        <input type="submit" value="Logout" />
    </form>
...

Now,how should I write the view for processing this form?If I am to process the hidden variables(confirm to check whether logout should be done and next to go to the previous view) ,will I still be able to use the django.contrib.auth.views.logout_then_login method?

can someone please tell me if I am doing this the right way?

thanks in advance


回答1:


You could wrap it like

from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.http import require_POST

@csrf_protect
@require_POST
@never_cache
def safer_logout(request):
    # 'confirm' is useless here, POST implies 'do it'
    return logout_then_login(request, request.POST.get('next'))

Also, consider using SESSION_COOKIE_HTTPONLY



来源:https://stackoverflow.com/questions/9930068/django-logout-using-a-link-or-form-to-prevent-csrf-exploit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!