我在使用 cURL 和 Postman 测试 Django rest api 时遇到问题。我正在使用 LoginRequiredMixin 来限制对我的 ClassView 的访问:
class UserList(LoginRequiredMixin, generics.ListCreateAPIView):
model = User
queryset = User.objects.all()
serializer_class = UserSerializer
当未经授权的用户尝试访问该页面时,他将被重定向到登录页面。URL 中有一个?next 参数,以便用户在授权后立即查看所需的页面。
/accounts/login/?next=/users/
问题是 cURL 和 Postman 可能甚至不使用提供的用户名和密码进行身份验证,而是立即重定向到作为结果返回的登录页面。
这是一个示例或 cURL 命令。即使提供了用户名和密码,结果也是 302 Found。当我为以下重定向添加 -L 参数时,它会从登录页面返回响应并且不会重定向回原始页面。
curl -i -L -u superadmin:superadmin http://127.0.0.1:8000/users/
HTTP/1.0 302 Found
Date: Fri, 13 Oct 2017 10:16:31 GMT
Server: WSGIServer/0.2 CPython/3.5.2
Vary: Cookie
Content-Length: 0
Content-Type: text/html; charset=utf-8
Location: /accounts/login/?next=/users/
X-Frame-Options: SAMEORIGIN
HTTP/1.0 200 OK
Date: Fri, 13 Oct 2017 10:16:31 GMT
Server: WSGIServer/0.2 CPython/3.5.2
Vary: Cookie
Content-Length: 1128
Content-Type: text/html; charset=utf-8
Cache-Control: max-age=0, no-cache, must-revalidate, no-store
X-Frame-Options: SAMEORIGIN
Expires: Fri, 13 Oct 2017 10:16:31 GMT
Set-Cookie: csrftoken=cCfAfsSlHOZEQGvPD1RR33r1UXj6JtEscWKFjmVyHmvVasqMx2J0pqyeNbVpY3X9; expires=Fri, 12-Oct-2018 10:16:31 GMT; Max-Age=31449600; Path=/
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form method="post" action="">
<table>
<tr>
<td><label for="id_username">Username:</label></td>
<td><input type="text" name="username" id="id_username" autofocus maxlength="254" required /></td>
</tr>
<tr>
<td><label for="id_password">Password:</label></td>
<td><input type="password" name="password" id="id_password" required /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Login" />
<input type="hidden" name="next" value="/private/meals/" />
<input type='hidden' name='csrfmiddlewaretoken' value='Pd3g7jmZ0WAACWihmRxNGvLF2wy5yzP9Pxylbdpc0u6RWIdegSpW2SSSVKaoN98Q' />
</td>
</tr>
</table>
</form>
<p><a href="/accounts/signup/">Sign up</a></p>
</body>
</html>
我尝试按照此处的建议保存和加载 cookie,但它也不起作用。有什么方法可以在 cURL 和 Postman 中传递 LoginRequiredMixin 吗?或者 Django Rest Framework 中适用于 Rest API 测试人员的访问限制的正确方法是什么。
谢谢