如何使用SessionAuthentication使用Django Rest Framework创建登录休息API?

jul*_*jul 12 django django-rest-framework

我想做一个休息api,以便能够使用类似的请求登录我的Django应用程序(来自Android应用程序)

curl -X POST -d "username=myusername&password=mypassword" http://localhost:12345/rest/api-auth/login/
Run Code Online (Sandbox Code Playgroud)

应该返回我可以在将来的请求中使用的会话ID.我似乎应该使用SessionAuthentication身份验证方案,但没有关于它的文档.

我知道这个问题,但我不想使用任何其他应用程序.

有什么建议/指针吗?

小智 5

/api-auth/login/资源仅用于浏览api中的身份验证.要使用会话身份验证,您必须首先创建会话.您必须具有登录资源,该资源使用Django身份验证系统接受用户凭据并对用户进行身份验证.在请求该资源时,客户端将获得cookie头.必须在将来的请求中使用cookie和csrf令牌.

curl -v -X POST https://example.com/api/user/login/ -d 'username=user&password=pass'

...

> Set-Cookie:  csrftoken=TqIuhp8oEP9VY32tUDcfQyUwn3cqpYCa; expires=Fri, 15-May-2015 12:48:57 GMT; Max-Age=31449600; Path=/
> Set-Cookie:  sessionid=4yb4s456lbvd974oijbdha7k3l6g52q3; expires=Fri, 30-May-2014 12:48:57 GMT; Max-Age=1209600; Path=/
Run Code Online (Sandbox Code Playgroud)

DRF也支持基本身份验证.您可以使用它来初始验证用户并创建会话.这是一个例子:

from django.contrib.auth import login

from rest_framework.authentication import BasicAuthentication, SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView


class MyBasicAuthentication(BasicAuthentication):

    def authenticate(self, request):
        user, _ = super(MyBasicAuthentication, self).authenticate(request)
        login(request, user)
        return user, _


class ExampleView(APIView):
    authentication_classes = (SessionAuthentication, MyBasicAuthentication)
    permission_classes = (IsAuthenticated,)

    def get(self, request, format=None):
        content = {
            'user': unicode(request.user),
            'auth': unicode(request.auth),  # None
        }
        return Response(content)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,但是我怎么用呢?我复制了你的代码,在我的 urls.py 中添加了 `url(r'^rest/login/$', views.ExampleView.as_view()),` 并在 `user, _ 中得到 `'NoneType' 对象不可迭代` = super(MyBasicAuthentication, self).authenticate(request)` 尝试 `curl -i -X POST http://127.0.0.1:8000/rest/login/ -d "user=user&password=pass"` 时 (3认同)
  • @jul 我现在有同样的问题,我发布了一个关于这个的问题,但我没有得到答案,你是如何实现的? (2认同)