如何从 django-oauth-toolkit 令牌获取当前登录的用户? [英] How can I get the current logged in user from a django-oauth-toolkit token?
问题描述
我正在使用 Django 和 django-oauth-toolkit 来构建一个通用的 OAuth2 授权服务器 用于 Auth0.我计划使用 Django 服务器对多个不同服务的用户进行身份验证,使用 Auth0 作为中介.
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'),
视图/current_user.py:
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
返回 AnonymousUser,而不是令牌所属的用户.
request.user
is returning AnonymousUser, instead of the user that the token belongs to.
如何访问与 django-oauth-toolkit 颁发的令牌关联的 Django 用户?
How can I access the Django user associated with a token issued by django-oauth-toolkit?
推荐答案
事实证明,如果您加载了正确的中间件和身份验证后端,就像这样 在文档中说,request.user 返回正确的用户.
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',
'...',
)
这篇关于如何从 django-oauth-toolkit 令牌获取当前登录的用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!