Login

JSON Web Token authentication middleware

Author:
andruwhart
Posted:
April 13, 2016
Language:
Python
Version:
1.7
Score:
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 users table.

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[0]
    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))

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

antonioiksi (on November 10, 2017):

for 'rest_framework_simplejwt' it wil be i that way:

from rest_framework.request import Request from rest_framework_simplejwt.authentication import JWTTokenUserAuthentication

def get_user_jwt(request): user = None try: user_jwt = JWTTokenUserAuthentication().authenticate(Request(request)) if user_jwt is not None: # store the first part from the tuple (user, obj) token_user = user_jwt[0] user_id = token_user.pk user = User.objects.get(id=user_id) except: pass return user

#

cyberpanther (on November 11, 2017):

I find this method using middleware more ideal. With the other implementations for JWT Auth it only works on Django REST API views. This gives JWT auth on any view.

#

Please login first before commenting.