djangodjango-rest-frameworkdjango-rest-framework-simplejwt

django simple jwt login with OTP without password


i have a django-rest app , for auth system i need help .
i want to use JWT for auth (simple_jwt) but i was reading the doc , that i have find that i need to send the password and user to get the token to get login .
this is a problem because users dont have the password i'm going to use OTP code to login users

I have searched the google and looks like i must code a backend i dont want to make it complicated i want as simple as it can be , i searched and i find something like knox too do it can help me out ?


Solution

  • I have searched and looked the simple_jwt package itself and made a solution for this problem to make JWT without password checking of package itself, or make a new backend. we can use the Token objects of simple_jwt for making the tokens, we just need to give a User instance to it, and it will make a token for us.

    from rest_framework_simplejwt.tokens import RefreshToken, AccessToken, BlacklistedToken
    from django.contrib.auth.models import User
    from rest_framework.views import APIView
    from rest_framework.response import Response
    
    
    class LoginView(APIView):
        # choice a user to build a token for him
        user = User.objects.get(username='Example')
    
        # access token for that user 
        access_token = AccessToken.for_user(user=user)
        # refresh token for that user 
        refresh_token = RefreshToken.for_user(user=user)
        
        return Response({'access': str(access_token),
                         'refresh': str(refresh_token)})
    

    NOTE: there is a problem with this way, you must authenticate the request your self, means for example if using one time password with OTP(SMS) you must check that user is sending right code or password then send him a token. After sending the token, its front-end job to handle the token in every request to send it in header. Another thing it don't need to make blacklist(logout) and refresh view for your self manual, you can use the built-in simple_jwt package, and they work fine.

    from rest_framework_simplejwt.views import TokenBlacklistView, TokenRefreshView
    from rest_framework import permissions
    
    # It get Refresh token and give new access and refresh token 
    class LogoutView(TokenBlacklistView):
        permission_classes = [permissions.IsAuthenticated]
    
    
    # It will put Refresh Token in blacklist
    class RefreshView(TokenRefreshView):
        permission_classes = [permissions.IsAuthenticated]
    
    

    Thanks.