如何从 django-oauth-toolkit 令牌获取当前登录用户?

How can I get the current logged in user from a django-oauth-toolkit token?

我正在使用 Django 和 django-oauth-toolkit 为 Auth0 构建通用 OAuth2 Authorization Server。我计划使用 Django 服务器对用户进行多种不同服务的身份验证,使用 Auth0 作为中介。

我有一个在应用程序通过身份验证后调用的视图,我需要该视图 return 当前登录用户的详细信息。

urls.py:

# Return current logged in user
(r'^user/current/?$',
 'my_app.views.current_user.get_user',
 {},
 'current_user'),

views/current_user.py:

import json
from django.http import HttpResponse
from oauth2_provider.decorators import protected_resource


@protected_resource()
def get_user(request):
    user = request.user
    return HttpResponse(
        json.dumps({
            'username': user.username, 
            'email': user.email}),
        content_type='application/json')

request.user 是 returning AnonymousUser,而不是令牌所属的用户。

如何访问与 django-oauth-toolkit 颁发的令牌关联的 Django 用户?

事实证明,如果您加载正确的中间件和身份验证后端,喜欢它 says in the documentation,request.user returns 正确的用户。

AUTHENTICATION_BACKENDS = (
'oauth2_provider.backends.OAuth2Backend',
# Uncomment following if you want to access the admin
#'django.contrib.auth.backends.ModelBackend'
'...',
)

MIDDLEWARE_CLASSES = (
    '...',
    # If you use SessionAuthenticationMiddleware, be sure it appears before OAuth2TokenMiddleware.
    # SessionAuthenticationMiddleware is NOT required for using django-oauth-toolkit.
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'oauth2_provider.middleware.OAuth2TokenMiddleware',
    '...',
)