【问题标题】:Authentication loop in django-rest-framework when accessing request.user访问 request.user 时 django-rest-framework 中的身份验证循环
【发布时间】:2015-01-14 15:32:42
【问题描述】:

我在 django-rest-framework 3.0.3 中定义了一个自定义身份验证方案,如下所示:

from django.contrib.auth.models import AnonymousUser
from rest_framework import authentication


class CustomAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        print 'authenticate!', request.user
        return (AnonymousUser(), None)

当我使用CustomAuthentication 时,我得到一个“超出最大递归深度”的错误,这会打印在我的日志中:

authenticate! authenticate! authenticate! authenticate! authenticate! etc.

从我的打印语句中删除request.user 修复了这个无限循环。定义自定义身份验证方案时我不应该使用request.user 吗?

【问题讨论】:

  • 您应该使用request.META.get('field') 从请求的标头中检索字段。
  • @cziemba 谢谢。当我做user = request.META.get('user') 时,userNone

标签: python django django-rest-framework django-1.7


【解决方案1】:

正如document 建议的那样:

request.user 通常返回一个实例 django.contrib.auth.models.User,虽然行为取决于 正在使用身份验证策略。

如果请求未经身份验证,则 request.user 的默认值为 django.contrib.auth.models.AnonymousUser 的一个实例。

我认为在使用 request.user 时,它会检查请求是否具有用户对象并递归地继续调用您的自定义身份验证方法。您需要在函数中返回 User 对象。

【讨论】:

猜你喜欢
  • 2019-07-29
  • 2019-01-01
  • 1970-01-01
  • 2013-05-03
  • 2021-09-09
  • 2015-11-12
  • 2015-12-26
  • 2020-04-10
  • 2015-06-01
相关资源
最近更新 更多