Skip to main content
 首页 » 编程设计

python之如何验证密码django rest

2025年01月19日25sky-heaven

我正在尝试制作一个休息应用程序来与我的 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"}) 

也许它对我找到的一些文章有帮助,但我不明白如何在 View 中实现它们(我重复我的专长是 android)

many options but I did not know how to implement

interesting but I did not understand how to implement the view

请您参考如下方法:

开始时,您不需要编写客户序列化程序进行验证,而是可以按照 token 基础身份验证在 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/ 发布用户名和密码,如果有效,您将获得一个 token 作为响应,响应状态将为 200 OK

如果你需要自定义响应那么你需要重写 post 方法 获取AuthToken如下:

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线程