- April 13, 2016
- middleware authentication json web token django-rest-framework JWT
- 0 (after 0 ratings)
This hasn't been thoroughly tested yet but so far it works great. We had no use for sessions or the built in authentication middleware for django as this was built to be a microservice for authentication. Unfortunately if you just use the django rest framework-jwt package the authentication occurs at the view level meaning request.user.is_authenticated() will always return False. We have a few internal non-api views that needed @login_required. We have a stripped down version of django that is very performant that we are using for microservices with built-in authorization using JSON Web Tokens. This service is authentication which has access to a
Any questions or curious how well lightweight django is working for microservices, or we he are doing the the authorization on the other services, or just improvements please drop a line - thanks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
from django.utils.functional import SimpleLazyObject from django.contrib.auth.models import AnonymousUser from rest_framework.request import Request from rest_framework_jwt.authentication import JSONWebTokenAuthentication def get_user_jwt(request): """ Replacement for django session auth get_user & auth.get_user JSON Web Token authentication. Inspects the token for the user_id, attempts to get that user from the DB & assigns the user on the request object. Otherwise it defaults to AnonymousUser. This will work with existing decorators like LoginRequired ;) Returns: instance of user object or AnonymousUser object """ user = None try: user_jwt = JSONWebTokenAuthentication().authenticate(Request(request)) if user_jwt is not None: # store the first part from the tuple (user, obj) user = user_jwt except: pass return user or AnonymousUser() class JWTAuthenticationMiddleware(object): """ Middleware for authenticating JSON Web Tokens in Authorize Header """ def process_request(self, request): request.user = SimpleLazyObject(lambda : get_user_jwt(request))