Skip to main content
 首页 » 编程设计

python之如何将 Django Rest Framework 与 contrib.auth View 连接起来

2024年08月21日30oomusou

我正在使用带有 JWT(JSON Web token )身份验证的 DRF。我想使用 django 的内置重置密码功能。所以,我已经包含了 url:

 url('^', include('django.contrib.auth.urls')), 

但是,当然,在 API 下,调用 https://.../password_reset/ 会导致 csrf token missing 错误。我想知道我应该采取哪种方法来解决这个问题。我应该更改内置的 reset_password View 并删除 csrf 保护吗?创建一个接受 email(reset_password 查看帖子参数)的 DRF 端点,然后以某种方式生成一个 csrf token 并使用 将其发送到 View 是否更好? >redirect(reverse("reset_password"), email=email) ... 但是,redirect 不会向 发送 post 请求reset_password 查看。也许将电子邮件保存到 session?任何建议都会有所帮助。

请您参考如下方法:

我认为在密码重置端点的情况下,移除 CSRF 保护是安全的。 CSRF 保护是针对经过身份验证的端点,以防止其他网站使用用户存储的凭据来获得未经授权的访问。自 PasswordResetForm Django 使用的密码除了发送电子邮件外不会做任何其他事情,攻击者除了通过向用户发送密码重置电子邮件垃圾邮件来骚扰用户外,真的做不了太多事情。

您可以为此使用第三方,但如果您所做的只是添加一个密码重置端点,您只需要几行代码。

View .py

import json 
 
from django.contrib.auth.forms import PasswordResetForm 
from django.http.response import HttpResponse 
from django.views.decorators.csrf import csrf_exempt 
from django.views.decorators.http import require_http_methods 
 
 
@csrf_exempt 
@require_http_methods(['POST']) 
def email_password_reset(request): 
    # the POST body should be in the format {'email': 'user@user.com'} 
    try: 
        # you could also uncomment the following line if you wanted this view to be anonymous only 
        # assert not request.user.is_authenticated() 
        assert request.META.get('CONTENT_TYPE', '') == 'application/json' 
        body = json.loads(request.body) 
    except (AssertionError, TypeError): 
        pass 
    else: 
        form = PasswordResetForm(body) 
 
        if form.is_valid(): 
            form.save() 
    finally: 
        return HttpResponse(status=200) 

网址.py

urlpatterns = patterns(... 
    url(r'^/api/password_reset/$', 'email_password_reset', name='email-password-reset') 
...)