【问题标题】:User Sessions in an oauth2 django appoauth2 django 应用程序中的用户会话
【发布时间】:2015-02-28 01:11:59
【问题描述】:

我使用 django、django rest 框架和 ember.js;我的整个应用程序因此通过 ajax 进行通信。

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

一切都很好,很闪亮,但文件下载。

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

我曾考虑将 SessionAuthentication 添加到该特定的 rest api 调用,但会话总是将传入用户标记为匿名用户。

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

我试过login(request, user),但不知何故无法启动。

【问题讨论】:

    标签: python django session


    【解决方案1】:

    我最终得到了签名票,例如我发回一个令牌,它能够在定义的时间范围内绕过身份验证。因此,ajax 应用程序可以首先请求令牌,然后再次触发带有令牌的标准获取请求。

    这是我在视图中混入的基本思想:

    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.')
    

    【讨论】:

      猜你喜欢
      • 2017-12-19
      • 2011-03-10
      • 2012-06-20
      • 2016-09-15
      • 1970-01-01
      • 2020-11-02
      • 1970-01-01
      • 1970-01-01
      • 2010-09-19
      相关资源
      最近更新 更多