如何验证密码django休息

时间:2018-04-07 05:19:42

标签: python django django-rest-framework

我正在尝试创建一个休息应用程序来与我的Android应用程序进行通信,但它阻止了我对密码的验证。

我默认使用django的用户模型,我想尝试让服务器验证密码

我找到了一些其他有趣的答案,但事实是django不是我的强项(我的专长是android)并且他们没有解释如何在我的视图中实现它们

restapp / views.py

class postRegister(APIView):

    def post(self,request):
        data = JSONParser().parse(request)
        cencripM=CriptoMovil(KEY_ENC_M)
        data['username'] = cencripM.decrypt(data['username'])
        data['email'] = cencripM.decrypt(data['email'])
        data['password'] = cencripM.decrypt(data['password'])
        serializer = RegistSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response({"message":"save","state":"1"})
        return Response({"message":serializer.errors,"state":"2"})

也许它有助于我发现的一些文章,但我不明白如何在视图中实现它们(我重复我的专业是android)

many options but I did not know how to implement

interesting but I did not understand how to implement the view

1 个答案:

答案 0 :(得分:1)

首先,您不需要编写客户序列化程序进行验证,而是可以按照令牌基本身份验证在android中进行验证,如下所示:

<强> urls.py

from rest_framework.authtoken.views import ObtainAuthToken

urlpatterns +=[
    url(r'^api-token-auth/', ObtainAuthToken.as_view(), name='get_auth_token')
]

现在您可以在/api-token-auth/发布用户名和密码,如果有效,您将获得一个响应中的令牌,响应状态为200 OK

如果您需要自定义响应,则需要覆盖post方法 ObtainAuthToken如下:

class CustomAuthentication(ObtainAuthToken): 
    def post(self, request, *args, **kwargs):
    serializer = self.serializer_class(data=request.data, context={'request': request})  # this will use DRF's AuthTokenSerializer and pass your request to it
    serializer.is_valid(raise_exception=True)  # validate serializer
    user = serializer.validated_data['user']  # you will get user instance if it is valid
    token, created = Token.objects.get_or_create(user=user)  # gives you token for user
    response_data = {'token': token.key}  #  create dict with token key
    # you can add any other JSON serializable details you want to add in this dict like username or related role/email
    return Response(response_data)

现在在urls.py而不是使用ObtainAuthToken.as_view(),您需要使用 CustomAuthentication.as_view()

有关其他设置详细信息,请阅读this主题