如何修复在 Django Rest Framework 中使用 REST API 登录时出现的 CSRF 错误?

Posted

技术标签:

【中文标题】如何修复在 Django Rest Framework 中使用 REST API 登录时出现的 CSRF 错误?【英文标题】:How to fix CSRF error on logging in using REST API in Django Rest Framework? 【发布时间】:2021-01-12 01:53:50 【问题描述】:

我是 Django 初学者,按照this 教程使用 DRF 实现注册、登录和注销。注册工作正常,但我无法使用邮递员登录,它显示 CSRF 错误。已经尝试使用 @csrf_exempt 装饰器,但随后它在 LoginAPI.asView() 上显示 AttributeError

AttributeError: 'function' 对象没有属性 'as_view'

<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="robots" content="NONE,NOARCHIVE">
  <title>403 Forbidden</title>
  <style type="text/css">
    html *  padding:0; margin:0; 
    body *  padding:10px 20px; 
    body * *  padding:0; 
    body  font:small sans-serif; background:#eee; color:#000; 
    body>div  border-bottom:1px solid #ddd; 
    h1  font-weight:normal; margin-bottom:.4em; 
    h1 span  font-size:60%; color:#666; font-weight:normal; 
    #info  background:#f6f6f6; 
    #info ul  margin: 0.5em 4em; 
    #info p, #summary p  padding-top:10px; 
    #summary  background: #ffc; 
    #explanation  background:#eee; border-bottom: 0px none; 
  </style>
</head>
<body>
<div id="summary">
  <h1>Forbidden <span>(403)</span></h1>
  <p>CSRF verification failed. Request aborted.</p>


  <p>You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.</p>
  <p>If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests.</p>

</div>

<div id="info">
  <h2>Help</h2>
    
    <p>Reason given for failure:</p>
    <pre>
    CSRF cookie not set.
    </pre>
    

  <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when
  <a
  href="https://docs.djangoproject.com/en/3.1/ref/csrf/">Django's
  CSRF mechanism</a> has not been used correctly.  For POST forms, you need to
  ensure:</p>

  <ul>
    <li>Your browser is accepting cookies.</li>

    <li>The view function passes a <code>request</code> to the template's <a
    href="https://docs.djangoproject.com/en/dev/topics/templates/#django.template.backends.base.Template.render"><code>render</code></a>
    method.</li>

    <li>In the template, there is a <code>% csrf_token
    %</code> template tag inside each POST form that
    targets an internal URL.</li>

    <li>If you are not using <code>CsrfViewMiddleware</code>, then you must use
    <code>csrf_protect</code> on any views that use the <code>csrf_token</code>
    template tag, as well as those that accept the POST data.</li>

    <li>The form has a valid CSRF token. After logging in in another browser
    tab or hitting the back button after a login, you may need to reload the
    page with the form, because the token is rotated after a login.</li>
  </ul>

  <p>You're seeing the help section of this page because you have <code>DEBUG =
  True</code> in your Django settings file. Change that to <code>False</code>,
  and only the initial error message will be displayed.  </p>

  <p>You can customize this page using the CSRF_FAILURE_VIEW setting.</p>
</div>

</body>
</html>

【问题讨论】:

【参考方案1】:

我不知道主要问题是什么,当你想使用登录 API 时,不要在你的 url 和你的请求中使用斜杠。

我已经得到了答案。

【讨论】:

这没有提供问题的答案。一旦你有足够的reputation,你就可以comment on any post;相反,provide answers that don't require clarification from the asker。 - From Review【参考方案2】:

根据错误:

AttributeError: el objeto 'función' no tiene atributo 'as_view'

... View 不是基于类的视图,或者如果是,您应该聚合 method_decorator 以便能够使用 csrf_exempt 装饰器,因为最后一个仅适用于基于函数的视图.

@method_decorator(csrf_exempt, name='method_name')
def View():

【讨论】:

以上是关于如何修复在 Django Rest Framework 中使用 REST API 登录时出现的 CSRF 错误?的主要内容,如果未能解决你的问题,请参考以下文章

如何修复在 Django Rest Framework 中使用 REST API 登录时出现的 CSRF 错误?

如何修复 Django Rest API 错误?

从 Django django-rest-framework 视图有条件地返回 JSON 或 HTML 响应

如何修复 Python(Django Rest 框架模板)中的 UnicodeDecodeError?

如何修复 Reactjs、Django、Django Rest Frame 工作项目中的“net::ERR_CONNECTION_REFUSED 和错误:网络错误”错误

修复 Django Rest Framework 模型序列化程序相关主键查询集中的错误