【问题标题】:How can I know where the request.user from in Django View?我如何知道 Django View 中的 request.user 来自哪里?
【发布时间】:2017-11-29 03:33:44
【问题描述】:

我如何知道 request.user 来自哪里?

我有一个 TestRequestUserAPIView:

class TestRequestUserAPIView(View):

    def dispatch(self, request, *args, **kwargs):
        result = super(TestRequestUserAPIView, self).dispatch(request, *args, **kwargs)
        return result

    def get(self, request):
        user = request.user  # this line I get the user (who access the API)
        return HttpResponse("ok")

当它执行这一行时user = request.user。 我可以得到请求user(谁请求这个API)。

我想知道用户如何生成请求,为什么我在 Chrome 等浏览器中请求这个 API,我的请求会有用户属性?

是通过 cookie 吗?或一些令牌(在我的测试项目中,我登录了。但是我在访问API时没有将令牌放入请求中,仍然在后端reqest.user中获取用户)?


编辑 -1

我的项目中有 django build-in auth 和 rest-auth

下面的身份验证在我的 INSTALLED_APPS 中:

'django.contrib.auth',
'rest_auth',
'allauth',
'allauth.account',
'allauth.socialaccount',
'rest_auth.registration',

我也想知道前端通过什么来识别用户,它使用cookie吗?还是令牌?我在登录时使用 rest-auth 生成令牌。

【问题讨论】:

    标签: python django


    【解决方案1】:

    我假设您使用的是Django's built-in authentication system - 即您的设置中包含了django.contrib.auth 安装的应用程序。

    中间件有机会在您的任何视图接收到 request 之前拦截它。 这个request.user属性是由Django的auth中间件here设置的:

    class RemoteUserMiddleware(MiddlewareMixin):
        """
        Middleware for utilizing Web-server-provided authentication.
        If request.user is not authenticated, then this middleware attempts to
        authenticate the username passed in the ``REMOTE_USER`` request header.
        If authentication is successful, the user is automatically logged in to
        persist the user in the session.
        The header used is configurable and defaults to ``REMOTE_USER``.  Subclass
        this class and change the ``header`` attribute if you need to use a
        different header.
        """
        ...
        def process_request(self, request):
            ...
            # We are seeing this user for the first time in this session, attempt
            # to authenticate the user.
            user = auth.authenticate(request, remote_user=username)
            if user:
                # User is valid.  Set request.user and persist user in the session
                # by logging the user in.
                request.user = user
                auth.login(request, user)
    

    【讨论】:

    • 感谢您的回答,我可以在我的项目中调试您的邮政编码吗?
    • 是的,您可以,只需在本地安装中找到django/contrib/auth/middleware.py 文件并在其中设置断点即可。
    • 说实话,我也想知道前端通过什么后端来识别用户,它使用cookie吗?还是令牌?我在登录时使用 rest-auth 生成令牌。
    • 它同时使用两者(cookie 中的会话令牌)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 2020-09-20
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多