Django Rest Framework中的自定义身份验证



我有一个django-rest框架应用程序,实现了自定义身份验证方案。现在我想允许外部应用程序调用我的应用程序的一些方法。外部应用登录/外部应用登录有一个端点,实现方式如下:

class ExternalAppLoginView(views.APIView):
def post(self, request):
if request.data.get('username') == EXTERNAL_APP_USER_NAME and request.data.get('password') == EXTERNAL_APP_PASSWORD:
user = models.User.objects.get(username=username)
login(request, user)
return http.HttpResponse(status=200)
return http.HttpResponse(status=401)

现在我想添加身份验证。我是这样实现的:

class ExternalAppAuthentication(authentication.SessionAuthentication):
def authenticate(self, request):
return super().authenticate(request)

但是身份验证总是失败。正确的方法是什么?我想将外部应用程序的登录名/密码存储在应用程序中的变量中,而不是数据库中。

身份验证失败,因为它需要返回数据库中的注册用户进行身份验证。然而,由于用户信息都在变量中,而不是数据库中,因此出现了问题。

克服这个问题的方法不止一种。首先,我建议您编写身份验证代码,而不是使用return super().authenticate(request),因为这将引导您找到问题的真正原因。

还必须提供一个阅读此文档链接,它清除了许多有关身份验证的内容。

https://www.django-rest-framework.org/api-guide/authentication/

现在,在完成所有这些操作并寻求如何进行身份验证后,您可以尝试远程用户身份验证,也可以检查变量中的现有用户并使用匿名用户进行身份验证,从而解决问题。

最新更新