Jon*_*uys 2 django oauth auth0 django-oauth
我正在使用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'),
Run Code Online (Sandbox Code Playgroud)
意见/ 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')
Run Code Online (Sandbox Code Playgroud)
request.user 返回AnonymousUser,而不是令牌所属的用户.
如何访问与django-oauth-toolkit发出的令牌相关联的Django用户?
Jon*_*uys 10
事实证明,如果您加载正确的中间件和身份验证后端,就像文档中所述,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',
'...',
)
Run Code Online (Sandbox Code Playgroud)