【问题标题】:Authenticate an API call correctly with requests and sessions使用请求和会话正确验证 API 调用
【发布时间】:2019-08-12 12:37:35
【问题描述】:

我想在我编写的自定义视图中调用我自己的 API。通常我在 API 调用中使用 JWT 身份验证。不过,在这个特定的视图中,我想使用不同的身份验证。

我想让已登录的用户能够成功进行 get 调用(无需令牌)。未登录的用户应该无法拨打该电话。我尝试了基本身份验证和会话身份验证,但并没有真正让它发挥作用。

这是我对 API 调用的看法:

def visualize_buildings(request, id):
    passed_id = id
    endpoint = 'linktomyendpoint' + str(passed_id)

    response = requests.get(endpoint)
    building_group_data = response.json()
    # print(building_group_data)

    if 'buildings' in building_group_data:
        building_data       = building_group_data['buildings']
        context = {'building' : building_data}
        return render(request, 'building_group_visualize_api.html', context)
    else:
        return HttpResponseNotFound("Ups. We are sorry but no Building Group was found with that id")

这里是我的 API 视图:

class BuildingGroupRetrieveAPIView(RetrieveAPIView):

    authentication_classes = [JSONWebTokenAuthentication, 
 SessionAuthentication, BasicAuthentication]
    serializer_class = BuildingGroupSerializer
    queryset = BuildingGroup.objects.all()

如果我在标头中发送令牌,则视图可以使用。但是我怎样才能使用会话身份验证呢?我尝试从请求中获取用户名和密码,然后将其传递给 API 调用。但这不起作用,因为我无法从请求中解码密码(这是有道理的)。 所以我试着遵循这个:https://2.python-requests.org/en/master/user/advanced/ 但我仍然无法验证我的请求。

谁能指出我正确的方向?非常感谢您的帮助!提前致谢!

【问题讨论】:

    标签: python django authentication django-rest-framework python-requests


    【解决方案1】:

    会话 ID 在用户设备上保存为 cookie,并将作为标题名称 Cookie 发送到服务器。因此,如果您想使用 cookie 而不是 JWT 令牌,那么您应该使用会话 ID 作为 cookie 标头发送请求。

    当您直接访问该站点时,这是让 Django 知道您的会话 ID 的标头:

    Cookie: csrftoken=some-csrf-token; sessionid=your-session-id
    

    现在让您的请求包含类似的内容:

    cookies = {'sessionid': 'your-session-id'}
    response = requests.get(endpoint, cookies=cookies)
    

    请注意,根据您的设置,Django 可能仍会出现 csrf 令牌错误。

    您可以在浏览器上找到您的会话 ID。如果您不知道在哪里以及如何访问它们,只需 google 即可。根据您使用的浏览器而有所不同。

    【讨论】:

    • Navid,非常感谢我的朋友。我一回到我的电脑就试试这个,让你知道它是怎么回事!谢谢!不过有一个问题:是否不需要创建会话对象,就像这里解释的那样:2.python-requests.org/en/master/user/advanced
    • 没问题。 Django 没有创建或设置任何 session-id 的 API,它在登录时进行。所以你必须使用自己的会话 ID 或手动创建一个。
    • 感谢您的澄清。我现在试过了。使用 session_id = request.session.session_key 获得了我的会话密钥,将其保存到一个变量中,并按照您的建议将其传递到我的请求中。完美地工作。非常感谢,真的帮了我大忙!
    猜你喜欢
    • 1970-01-01
    • 2021-12-03
    • 2021-08-11
    • 2021-08-31
    • 1970-01-01
    • 2016-01-26
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多