【问题标题】:How to add a filter in django for every request?如何在 django 中为每个请求添加过滤器?
【发布时间】:2021-02-03 08:41:21
【问题描述】:

我想添加一个安全过滤器,以便对我的 django 应用程序的每个请求都将首先通过过滤器,然后如果标头中的令牌有效,则让请求通过。

我怎样才能在 django 中做到这一点?

谢谢。

【问题讨论】:

    标签: python django http security


    【解决方案1】:

    你可以像这样添加一个新的中间件:

    class SecurityMiddleware:
        def __init__(self, get_response):
            self.get_response = get_response
    
        def __call__(self, request):
            token = request.META.get('HTTP_AUTHORIZATION')
            if token != "Some Value":
                 return HttpResponse('Unauthorized', status=401)
            response = self.get_response(request)
            return response
    

    然后将此添加到settings.py 中的MIDDLEWARE

    MIDDLEWARE = [
        ...
        'path.to.SecurityMiddleware'
    ]
    

    更多信息可以在custom middleware 文档和request and response object 文档中找到。

    仅供参考,如果您想实现标准身份验证系统(如 JWT 或基本身份验证),请考虑使用第三方库(如 Simple JWT 和 Django Rest Framework 等)。

    【讨论】:

      猜你喜欢
      • 2016-01-19
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-25
      • 2020-11-14
      • 2021-02-14
      相关资源
      最近更新 更多