Will & Skill Developers

Will & Skill Developers


Thoughts, snippets and ideas from the team at Will & Skill AB, Stockholm.

Erik Svedin
Author

Share


User creation and JWT

Erik SvedinErik Svedin

JWT is a great way to authenticate users, its especially handy when your API serves a mobile app as well as a website. Its basicallly just a hashed string that is added either as a header or as a GET parameter to every request that needs authentication.

Using django-rest-framework in conjunction with django-rest-framework-JWT its extremely easy to get started, they've already created ready to use endpoints where you simply post a users credentials, and as a return you recieve the JWT token for your next requests.

However what if we want to generate the token ourselves? For instance when a user is created we want to be able to log them in immediately, in order to do that using JWT we must go through a few steps, nothing too complicated though.

  1. Recieve user data, validate and create the user.
  2. Generate a JWT token based on the created user.
  3. Return the token to the frontend which saves it, so that we can make authenticated requests.

Enough writing, heres the code:

First import the JWT_PAYLOAD_HANDLER and JWT_ENCODE_HANDLER.

from rest_framework_jwt.settings import api_settings

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER  
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER  

Then create the user as you normally would, and use the JWT_PAYLOAD_HANDLERand JWT_ENCODE_HANDLERto generate a token which gets returned to the frontend. Easy as pie!

class RegisterUser(APIView):  
    permission_classes = (AllowAny,)
    serializer_class = UserCreationSerializer

    def post(self, request):
        serializer = self.serializer_class(data=request.DATA)

        if serializer.is_valid(raise_exception=True):
            user = User.objects.create_user(
                serializer.init_data['email'],
                serializer.init_data['password']
            )

            payload = jwt_payload_handler(user)
            jwt_token = jwt_encode_handler(payload)

            return Response({'jwt_token':jwt_token}, status=status.HTTP_201_CREATED)
Erik Svedin
Author

Erik Svedin

Comments