Django 自定义中间件 request.user 总是 AnonymousUser
Django custom middleware request.user always AnonymousUser
我正在使用 Django 2.2 和 DRF
在我的应用程序中,基于用户 属性,我需要将 request.user
更改为其他用户。
class CustomMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
print(request.user)
response = self.get_response(request)
return response
print(request.user)
始终提供 AnonymousUser
对象,但它在视图中提供经过身份验证的用户。
如何获取中间件中的用户?
中间件层次结构
MIDDLEWARE = [
'django_hosts.middleware.HostsRequestMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'silk.middleware.SilkyMiddleware',
'django_hosts.middleware.HostsResponseMiddleware',
'oauth2_provider.middleware.OAuth2TokenMiddleware',
'myapp.middleware.CustomMiddleware',
]
通过使用 oauth2_provider.backends.OAuth2Backend
到 AUTHENTICATION_BACKENDS
列表来解决它。
AUTHENTICATION_BACKENDS = (
'oauth2_provider.backends.OAuth2Backend',
# Uncomment following if you want to access the admin
#'django.contrib.auth.backends.ModelBackend'
'...',
)
我正在使用 Django 2.2 和 DRF
在我的应用程序中,基于用户 属性,我需要将 request.user
更改为其他用户。
class CustomMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
print(request.user)
response = self.get_response(request)
return response
print(request.user)
始终提供 AnonymousUser
对象,但它在视图中提供经过身份验证的用户。
如何获取中间件中的用户?
中间件层次结构
MIDDLEWARE = [
'django_hosts.middleware.HostsRequestMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'silk.middleware.SilkyMiddleware',
'django_hosts.middleware.HostsResponseMiddleware',
'oauth2_provider.middleware.OAuth2TokenMiddleware',
'myapp.middleware.CustomMiddleware',
]
通过使用 oauth2_provider.backends.OAuth2Backend
到 AUTHENTICATION_BACKENDS
列表来解决它。
AUTHENTICATION_BACKENDS = (
'oauth2_provider.backends.OAuth2Backend',
# Uncomment following if you want to access the admin
#'django.contrib.auth.backends.ModelBackend'
'...',
)