oauth2Django应用程序中的用户会话

2024-09-26 18:13:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用django、django rest框架和余烬;我的整个应用程序通过ajax进行通信。在

身份验证通过oauth2完成,并且在每个请求的头中发送一个令牌。在

所有的一切都很好,闪亮,但文件下载。在

用户可以下载pdf文件,但我不知道如何在那里应用身份验证-因为在文件下载时,我无法发送和邮件头,它只是一个链接。在

我曾想过向特定的restapi调用添加SessionAuthentication,但会话总是将传入用户标记为anyonymous。在

如何强制django在oauth2令牌流上创建会话?在

我试过login(request, user),但不知怎么的它没有起作用。在


Tags: 文件django用户框架身份验证restrestapi应用程序
1条回答
网友
1楼 · 发布于 2024-09-26 18:13:59

最后我得到了签名的票证,例如,我发回一个令牌,它可以在规定的时间范围内绕过auth。因此,ajax应用程序可以首先请求令牌,然后再使用附加的令牌来触发一个标准的get请求。在

以下是我融合到视图中的基本思想:

class DownloadableMixin():
    """
    Manages a ticket response, where a ticket is a signed response that gives a user limited access to a resource
    for a time frame of 5 secs.

    Therefore, file downloads can request a ticket for a resource and gets a ticket in the response that he can
    use for non-ajax file-downloads.
    """

    MAX_AGE = 5

    def check_ticket(self, request):
        signer = TimestampSigner()
        try:
            unsigned_ticket = signer.unsign(request.QUERY_PARAMS['ticket'], max_age=self.__class__.MAX_AGE)
        except SignatureExpired:
            return False
        except BadSignature:
            return False

        if self.get_requested_file_name() == unsigned_ticket:
            return True
        return False

    def get_ticket(self):
        signer = TimestampSigner()
        return signer.sign(self.get_requested_file_name())

    def has_ticket(self, request):
        return 'ticket' in request.QUERY_PARAMS

    def requires_ticket(self, request):
        return 'download' in request.QUERY_PARAMS

    def get_requested_file_name(self):
        raise NotImplementedError('Extending classes must define the requested file name.')

相关问题 更多 >

    热门问题