问题
I wrote a simple JWT middleware to get user from the JWT. The method get_user_from_jwt
returns a User object.
# app.middlewares.py
class JwtMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
self.process_request(request)
return self.get_response(request)
def process_request(self, request):
request.user = self.get_user_from_jwt(request.headers)
def get_user_pk_from_jwt(self, auth_header: str) -> int:
_, token = auth_header.split(' ')
decoded_payload = jwt.decode(token, settings.SECRET_KEY)
user_pk = decoded_payload.get('user_id', None)
return user_pk
def get_user_from_jwt(self, auth_header: str) -> User:
auth_header = headers.get('Authorization', None)
if auth_header:
try:
user_pk = self.get_user_pk_from_jwt(auth_header)
user = get_object_or_404(User, pk=user_pk)
return user
except Exception as error:
logging.error(f'Error decoding JWT due to: {str(error)}')
raise AuthenticationFailed
else:
raise NotAuthenticated
In settings:
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'app.middlewares.JwtMiddleware',
]
When I log, request.user
is set to the proper User instance at the middleware level, but once at a view, request.user
becomes AnonymousUser. I tried switching the orders of the middlewares too. Any ideas how I can update what request.user means inside my views using a middleware?
回答1:
If you are using JWT token authentication with Django rest framework, then you need to update your authentication backends. The request.user is set automatically, when a user is authenticated. So if you are not authenticating the user, your request.user will be over-written by AnonymousUser.
You need to write an authentication Class, for example, JWTAuth, which should inherit the BaseAuthetication.
from rest_framework import authentication, exceptions
class JWTAuth(authentication.BaseAuthentication):
authentication_header_prefix = 'Bearer'
def authenticate(self, request):
request.user = None
auth_header = authentication.get_authorization_header(request).split()
auth_header_prefix = self.authentication_header_prefix.lower()
if not auth_header:
return None
prefix = auth_header[0].decode('utf-8')
token = auth_header[1].decode('utf-8')
if prefix.lower() != auth_header_prefix:
return None
return self._authenticate_credentials(request, token)
def _authenticate_credentials(self, request, token):
try:
payload = jwt.decode(token, settings.SECRET_KEY)
except:
msg = 'Invalid authentication. Could not decode token.'
raise exceptions.AuthenticationFailed(msg)
try:
user = User.objects.get(pk=payload['id'])
except User.DoesNotExist:
msg = 'No user matching this token was found.'
raise exceptions.AuthenticationFailed(msg)
if not user.is_active:
msg = 'This user has been deactivated.'
raise exceptions.AuthenticationFailed(msg)
return user, token
in your settings file
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'JWTAuth',
)
If you are also trying to customize your Login process, then you will have to update AUTHENTICATION_BACKENDS in your settings file.
来源:https://stackoverflow.com/questions/62111926/middleware-updates-request-user-but-request-user-becomes-anonymoususer-in-view