0

cURL と Postman を使用して Django REST API をテストする際に問題が発生しています。ClassView へのアクセスを制限するために LoginRequiredMixin を使用しています。

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 を渡す方法はありますか? または、Rest API テスターで動作する Django Rest Framework でのアクセス制限の適切な方法は何ですか。

ありがとうございました

4

2 に答える 2