Search code examples
djangodjango-rest-framework-jwt

Django TokenAuthentication - extending JWT obtain_jwt_token


I have a Django REST app and token authentication powered by Django REST framework JWT Auth

Let me formulate my high-level goal:

My goal is to generate a token for the user if he provides correct credentials AND THEN immediately after successful login I want to perform some additional set of operations. For simplicity, let's say I want to print "Hello" to the console.

Right now my code looks like this:

from rest_framework_jwt.views import obtain_jwt_token

urlpatterns = [
    url(r'^api-token-auth/', obtain_jwt_token),
]

What I want to do is the following

  1. Get the token that obtain_jwt_token generates
  2. If authentication was successful, do some additional operations and return the token to the user.

I feel lost in the jungles of all this Django architecture related to authentication classes. Do I understand correctly that if I am using third-party packages like Django JWT, I have no power on login process and there's no way to perform additional operations after the user logs in? And if I want to have more power on login process, I have to do all the job that Django JWT developers have done from scratch? Can I somehow add some operations ON TOP of Django JWT's obtain_jwt_token ?


Solution

  • obtain_jwt_token is just a reference to a view, and as with any view you can just subclass it and reference that instead

    class MySpecialJWT(ObtainJSONWebToken):
        def post(self, request, *args, **kwargs):
            response = super().post(request, *args, **kwargs)
            # foo bar
            return response