How to authenticate android user POST request with Django REST API?
到目前为止,我已经有了Django REST API,并且对于Web应用程序来说一切都是虚假的,其中我已经在后端实现了User Auth。 " login_required "条件非常适合基于cookie的Web应用。
我现在有一个Android应用程序,需要访问相同的API。我可以登录用户。我需要知道的是如何在每个用户向我的视图发出GET / POST请求时对每个用户进行身份验证?
我的研究显示了两种解决方案:
1)Cookie支持的会话
2)在每个GET / POST请求中发送用户名和密码(可能不安全)
有什么想法吗?
听起来您正在使用Django REST Framework,在这种情况下,TokenAuthentication可能是合适的。
从文档:
This authentication scheme uses a simple token-based HTTP
Authentication scheme. Token authentication is appropriate for
client-server setups, such as native desktop and mobile clients
您不需要预先生成令牌,因为客户端可以使用您在urls.py中配置的内置视图
客户端获得会话的令牌后,便可以使用
查看文档以获取更多信息:http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication
HTTP Basic authentication (BA) implementation is the simplest
technique for enforcing access controls to web resources because it
doesn't require cookies, session identifier and login pages. Rather,
HTTP Basic authentication uses static, standard HTTP headers which
means that no handshakes have to be done in anticipation
要了解更多信息并了解在服务器和客户端上要实现的目标,请阅读以下内容:
http://en.wikipedia.org/wiki/Basic_access_authentication
我使用了不同的REST Java框架,它们都提供了简单的API以添加基本身份验证标头的添加和检索。
对于Django,以下是一些有用的代码段:
http://djangosnippets.org/snippets/243/
您可能想使用Django Sessions中间件,它将使用django session_id设置cookie。在以下请求上,会话中间件将在您的请求对象上设置一个名为user的属性,然后您可以测试用户是否已通过request.user.is_authenticated()(或login_required装饰器)进行身份验证。另外,您可以将会话超时设置为您喜欢的设置。
在默认的django设置中启用了此中间件。