问题
I'm using Django and django-oauth-toolkit to build a generic OAuth2 Authorization Server for Auth0. I plan to use the Django server to authenticate users to several different services, using Auth0 as an intermediary.
I have a view that is called after an application has authenticated, and I need that view to return the details of the currently logged-in user.
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 is returning AnonymousUser, instead of the user that the token belongs to. 
How can I access the Django user associated with a token issued by django-oauth-toolkit?
回答1:
Turns out, if you load the correct middleware and authentication backend, like it says in the documentation, request.user returns the correct user.
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',
    '...',
)
来源:https://stackoverflow.com/questions/39906719/how-can-i-get-the-current-logged-in-user-from-a-django-oauth-toolkit-token