0

我有一个小函数,它只是看起来从我的 DRF API 端点获得响应。

我的 DRF 设置如下所示:

    "DEFAULT_AUTHENTICATION_CLASSES": [
        # Enabling this it will require Django Session (Including CSRF)
        "rest_framework.authentication.SessionAuthentication"
    ],
    "DEFAULT_PERMISSION_CLASSES": [
        # Globally only allow IsAuthenticated users access to API Endpoints
        "rest_framework.permissions.IsAuthenticated"
    ],

我正在使用它来尝试达到终点:

def get_car_details(car_id):
    headers = {"X-Requested-With": "XMLHttpRequest"}
    api_app = "http://localhost:8000/"
    api_model = "cars/"
    response = requests.get(api_app + api_model + str(car_id), headers=headers)
    json_response = response.json()
    return json_response

我不断得到'detail': 'Authentication credentials were not provided'

我是否需要生成 CSRF 令牌并将其包含在 GET 请求中?唯一一次被击中是当用户进入需要他们登录的视图时。有没有办法将该登录用户传递到端点?

4

1 回答 1

0

当您从get_car_details函数发出请求时,您需要确保请求已通过身份验证。这看起来不像是 CSRF 问题。

使用基于会话的身份验证时,会在登录后传回会话 cookie。因此,在您调用之前,您get_car_details需要首先发出登录请求,保持该会话,并在调用 API 时使用该会话。

Requests 有一个requests.Session()可以用于此目的的会话类。此处的详细信息:https ://docs.python-requests.org/en/latest/user/advanced/

许多人发现基于令牌的身份验证更容易,部分会话 cookie 不需要维护。

于 2021-12-02T21:44:41.733 回答