简体   繁体   English

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

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

I'm using Django and django-oauth-toolkit to build a generic OAuth2 Authorization Server for Auth0. 我正在使用Django和django-oauth-toolkit为Auth0构建一个通用的OAuth2授权服务器 I plan to use the Django server to authenticate users to several different services, using Auth0 as an intermediary. 我计划使用Django服务器来验证几个不同服务的用户,使用Auth0作为中介。

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: urls.py:

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

views/current_user.py: 意见/ 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. request.user返回AnonymousUser,而不是令牌所属的用户。

How can I access the Django user associated with a token issued by django-oauth-toolkit? 如何访问与django-oauth-toolkit发出的令牌相关联的Django用户?

Turns out, if you load the correct middleware and authentication backend, like it says in the documentation , request.user returns the correct user. 事实证明,如果您加载正确的中间件和身份验证后端,就像文档中所述 ,request.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',
    '...',
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM