Django check CSRF token manually

后端 未结 4 1007
伪装坚强ぢ
伪装坚强ぢ 2021-02-08 02:27

I am implementing an API that works either with an API key, or with a CSRF token. The goal is for it to be usable either by a web app (protected by CSRF) or by a third party app

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-08 03:04

    You could probably subclass the CsrfViewMiddleware class and override the process_view method. Then include your custom middleware instead of the default CSRF one.

    from django.middleware.csrf import CsrfViewMiddleware
    
    class CustomCsrfMiddleware(CsrfViewMiddleware):
    
        def process_view(self, request, callback, callback_args, callback_kwargs):
            if request.META.get('api_key'):
                # process api key
            else:
                return super(CsrfViewMiddleware, self).process_view(...)
    

提交回复
热议问题