在Django Rest框架中实现会话身份验证?

时间:2020-01-22 15:39:16

标签: django authentication session django-rest-framework

我正在尝试在drf中实现基于会话的身份验证。 我没有从django会话文档以及drf文档中了解任何内容。 我想要一个用于登录,注销和列出所有用户的API端点。

class Login(APIView):

def post(self, request, format=None):
    email = request.POST.get("email", "")
    print(request.session)
    password = request.POST.get("password", "")
    user = authenticate(request,username=email,password=password)
    if user is not None:
        login(request,user)
        print(user)
        return Response('yes')
    else :
        return Response('No')


class UserList(APIView):
authentication_classes = (SessionAuthentication,)
permission_classes = [
    IsAuthenticated,
    ]


def get(self, request, format=None):

    user = User.objects.all()
    print(request.user)
    serializer = UserSerializer(user, many=True)

    return Response(serializer.data)

Settings.py

MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

我尝试从浏览器调用登录api。 是的,它已登录 现在,当我尝试致电Userlist视图时 未提供身份验证详细信息错误

我的用于请求用户的客户端服务器代码(js)

var myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
    console.log(Document.cookie);
    var urlencoded = new URLSearchParams();

    var requestOptions = {
      method: 'GET',
      credentials: 'include',
       headers: myHeaders,
      redirect: 'follow'
    };

    fetch("http://127.0.0.1:8000/api/", requestOptions)
      .then(response => response.text())
      .then(result => console.log(result))
      .catch(error => console.log('error', error));

请帮助我了解drf中的会话。

0 个答案:

没有答案