Django手动检查CSRF令牌 [英] Django check CSRF token manually
问题描述
我正在实现与API密钥或CSRF令牌一起使用的API。目标是使其可以通过Web应用程序(受CSRF保护)或第三方应用程序(受API密钥保护)使用。
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 application (protected by API key).
基本上在每次请求时(全部通过POST),我检查是否有API密钥。如果有一个有效的,那就去吧。如果没有,我想回过头来验证CSRF。
Basically on each request (all via POST), I check if there is an API key. If there is a valid one, it's good to go. If not, I want to fall back to verifying CSRF.
我可以调用一个函数来验证CSRF吗?该视图本身为 @csrf_exempt
,因为API密钥需要工作。
Is there a function I can call to verify the CSRF myself? The view itself is @csrf_exempt
because API keys need to work.
推荐答案
您可能可以继承CsrfViewMiddleware类并重写process_view方法。然后包括您的自定义中间件,而不是默认的CSRF。
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(...)
这篇关于Django手动检查CSRF令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!