【问题标题】:JWT Authentication with Django REST Framework using otp for getting api tokens使用 otp 获取 api 令牌的 Django REST 框架的 JWT 身份验证
【发布时间】:2021-07-06 10:11:57
【问题描述】:

我有一个自定义用户登录,我使用移动 OTP 验证,并且在我的项目中根本不使用任何 django 用户模型。需要通过 otp 对 jwt django restframework 进行身份验证。请帮我解决一下这个。 谢谢

【问题讨论】:

  • 你可以展示你的代码,你想要做什么

标签: python-3.x django django-rest-framework jwt


【解决方案1】:

首先发送 otp 并将其保存到数据库中。

class LoginView(APIView):
    def post(self, request, format=None):
        data = request.data
        response = Response()       
        username = data.get('username', None)
        password = data.get('password', None)
        user = authenticate(username=username,password=password)
        if user is not None:
            if user.is_active:
                if user.two_step_verification:

                    GENERATE OTP HERE AND SAVE THIS IN USER MODEL...

                    user.otp = 'YOUR OTP'
                    user.save(update_fields=['otp',]) 
                    
                    SEND OTP HERE...                       
             
                    return Response({"send":"Two step verification OTP successfully send!!!"},status = status.HTTP_200_OK) 
            else:
                return Response({"No active" : "This account is not active!!"},status=status.HTTP_404_NOT_FOUND)
        else:
            return Response({"Invalid" : "Invalid username or password!!"},status=status.HTTP_404_NOT_FOUND)

然后验证这一点。 这里我使用rest_framework_simplejwt

from rest_framework_simplejwt.tokens import RefreshToken

@api_view(['POST'])
@permission_classes([AllowAny,])
def two_step_otp_Verify(request,otp):
    try:
        user = User.objects.get(otp = otp,is_active = True)
        verify = 'VERIFY YOUR OTP HERE'
        if verify:
            response = Response()
            user.otp = None
            user.last_login = timezone.now()
            user.save()
            refresh = RefreshToken.for_user(user)
            
            response.set_signed_cookie(
                       key = 'ACCESS_TOKEN', 
                       value = str(refresh.access_token),
                       .....
                       )
            #ORRRRRRRRRRRRRRRRRRRRRRR
            login(request, user)
            
            response.data = {"Success" : "Login successfully"}
            return response
        else:
            return Response({"Time out" : "Given otp is expired!!"}, status=status.HTTP_408_REQUEST_TIMEOUT)
    except:
        return Response({"No User" : "Invalid otp OR No any active user found for given otp"}, status=status.HTTP_400_BAD_REQUEST)

【讨论】:

    猜你喜欢
    • 2018-12-15
    • 2023-03-16
    • 2021-10-27
    • 2019-03-01
    • 2021-12-21
    • 2019-07-11
    • 2019-04-22
    • 2019-02-27
    • 2019-05-02
    相关资源
    最近更新 更多