gpt4 book ai didi

django - 如何使用 SessionAuthentication 通过 Django Rest Framework 制作登录休息 API?

转载 作者:行者123 更新时间:2023-12-04 01:10:27 25 4
gpt4 key购买 nike

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

curl -X POST -d "username=myusername&password=mypassword" http://localhost:12345/rest/api-auth/login/

它应该返回一个我可以在以后的请求中使用的 session ID。看来我应该使用SessionAuthentication认证方案,但是有 no doc关于它。

我知道 this question ,但我不想使用任何其他应用程序。

任何建议/指针?

最佳答案

/api-auth/login/ 资源仅用于browseble api 中的身份验证。
要使用 session 身份验证,您必须先创建 session 。
您必须有一个登录资源,它接受用户凭据并使用 Django 身份验证系统对用户进行身份验证。
在请求该资源时,客户端将获得一个 cookie header 。
cookie 和 csrf token 必须在以后的请求中使用。

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=/

DRF 也支持基本身份验证。您可以使用它进行身份验证
用户最初并创建 session 。这是一个例子:
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)

关于django - 如何使用 SessionAuthentication 通过 Django Rest Framework 制作登录休息 API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23687643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com