【问题标题】:Auth token in URL pathURL 路径中的身份验证令牌
【发布时间】:2020-06-01 15:45:32
【问题描述】:

我正在使用 Django REST 框架 TokenAuthentication

对于一些 URL,我不得不在 URL 路径中包含令牌:

https://example.com/api/<auth_token>/something

所以 urlpatterns 是:

urlpatterns = [
    path('api/<auth_token>/something', views.SomeView.as_view()),
]

而观点是:

class SomeView(APIView):
    authentication_classes = (TokenAuthentication)
    permission_classes = (IsAuthenticated, )

    def get(self, request, auth_token):
    ...

但是TokenAuthentication 在这里不起作用,因为令牌在 URL 路径中,而不是在标头中。如果可能的话,我想扩展 TokenAuthentication 以处理 URL 内令牌。

【问题讨论】:

  • @RyanWilson 用一些代码澄清了这个问题。
  • 谢谢你,安德烈。

标签: django django-rest-framework


【解决方案1】:

首先,将身份验证令牌放在 url 中是不安全的,不推荐(url 最终出现在服务器日志和其他东西中)。

如果这是生死攸关的问题,我会做的是从 Django rest 扩展 TokenAuthentication 类,仅覆盖 authenticate 方法。如果您查看source code,它会从标头中获取令牌,运行一些验证并调用self.authenticate_credentials(token)。所以我会做这样的事情:

class UrlTokenAuthentication(TokenAuthentication):
    def authenticate(self, request):
        token = # get the token from the url path and check that has proper format, etc.
        return self.authenticate_credentials(token)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多