I'm having problems with testing Django rest api with cURL and Postman. I'm using LoginRequiredMixin to restrict access to my ClassView:
class UserList(LoginRequiredMixin, generics.ListCreateAPIView):
model = User
queryset = User.objects.all()
serializer_class = UserSerializer
When an unauthorised user tries to access the page he is redirected to login page. In the URL is a ?next parameter so that user views the desired page right after authorization.
/accounts/login/?next=/users/
Problem is that cURL and Postman probably don't even use provided user name and password for authentication and are immediately redirected to the login page which is returned as a result.
Here is an example or cURL command. Even though user name and password is provided the result is 302 Found. When I add -L parameter for following redirects it returns the response from login page and doesn't redirect back to original page.
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>
I tried saving and loading cookie as suggested here but it doesn't work either. Is there any way to pass the LoginRequiredMixin in cURL and Postman? Or what is the proper way of access restriction in Django Rest Framework that would work with Rest API testers.
Thank you
Do you have any idea how to do it with Postman. Also could you post it as an answer. I would do it, but don't want to take your credit. – Petr Hofman Oct 13 '17 at 13:48