Describe the bug
In my application, based on the user property, I need to change the request.user to a different 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
and the MIDDLEWARE stack is
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',
]
Rest Framework Configuration
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
]
}
The request.user in the CustomMiddleware gives AnonymousUser object even though user is authenticated. It gives user object in the views.
Same middleware is working fine when using admin panel.
Expected behavior
It should return the authenticated user.
Version
django-oauth-toolkit==1.3.0
Additional context
I'm having this issue too, it will only work if i will put it after the response
but i want to get it before the response
example:
class CustomMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
print(request.user)
return response
It only happen when grant_type=client_credentials
@anuj9196 i think you forgot to put the 'oauth2_provider.middleware.OAuth2TokenMiddleware' after 'django.contrib.auth.middleware.AuthenticationMiddleware' under the MIDDLEWARE
@BuSHari I have that middleware added to the list above CustomMiddleware.
I have updated the list in the first post.
Still getting anonymous user.
Authorization Grant Type is Resource owner password-based
I forgot to add the authentication backend. Adding authentication backed solved the issue
AUTHENTICATION_BACKENDS = (
'oauth2_provider.backends.OAuth2Backend',
# Uncomment following if you want to access the admin
#'django.contrib.auth.backends.ModelBackend'
'...',
)
Most helpful comment
I'm having this issue too, it will only work if i will put it after the response
but i want to get it before the response
example: