簡體   English   中英

如何從django-oauth-toolkit令牌獲取當前登錄用戶?

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

我正在使用Django和django-oauth-toolkit為Auth0構建一個通用的OAuth2授權服務器 我計划使用Django服務器來驗證幾個不同服務的用戶,使用Auth0作為中介。

我有一個在應用程序經過身份驗證后調用的視圖,我需要該視圖來返回當前登錄用戶的詳細信息。

urls.py:

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

意見/ 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返回AnonymousUser,而不是令牌所屬的用戶。

如何訪問與django-oauth-toolkit發出的令牌相關聯的Django用戶?

事實證明,如果您加載正確的中間件和身份驗證后端,就像文檔中所述 ,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