通过验证用户身份使用Django rest框架下载文件

JavaScript Vue.js

卡卡西Near

2020-03-24

我正在使用Django作为后端的项目中工作。我正在使用Django rest框架,并且有一个API可以下载文件。

@detail_route(methods=['GET'], permission_classes=[IsAuthenticated])
def test(self, request, pk=None):
    try:
        ticket = Ticket.objects.get(id=pk, user=request.user)
        file_path = ticket.qrcode_file.path
        if os.path.exists(file_path):
            with open(file_path, 'rb') as fh:
                response = HttpResponse(fh.read(), content_type="image/jpeg")
                name = "%s %s %s %s.jpg" % (ticket.show.title, datetime.strftime(ticket.show.date_time,
                                                                                       "%H_%M_%p"),
                                            datetime.strftime(ticket.show.date_time, "%d %B %Y"), ticket.id)
                response['Content-Disposition'] = "attachment; filename=%s" % name.replace(" ", "_")
                return response
        return Response({'error': 'Ticket doest not belong to requested user.'}, status=status.HTTP_403_FORBIDDEN)
    except Ticket.DoesNotExist as e:
        return Response({'error': str(e)}, status=status.HTTP_404_NOT_FOUND)

在前端,我正在使用Nuxtjs(用于vuejs的ssr)。这是一小段代码,用户可以通过单击目标空白的链接来下载文件:

<a class="downloadBtn" target="_blank" :href="`${baseURL}/payments/api/tickets/${ticket.id}/download_ticket/`">Download e-ticket</a>

该Web应用程序在Nuxtjs服务器(localhost:3000)上运行,而Django服务器在localhost:8000上运行,仅使用API​​通过auth令牌在Nuxtjs和Django之间进行通信。

当我单击下载链接时,它将打开一个新选项卡,并从该新选项卡发出请求,该请求中未传递任何令牌。而且,由于django视图无法下载票证,permission_classes=[IsAuthenticated]因此无法像request.user匿名身份一样对我进行身份验证

通过检查请求的用户是否是票证的所有者,还有其他方法可以使我下载文件吗?

第3309篇《通过验证用户身份使用Django rest框架下载文件》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0个回答

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android