Django check CSRF token manually

后端 未结 4 1005
伪装坚强ぢ
伪装坚强ぢ 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 02:58

    You can use builtin csrf verification like this:

    from django.middleware.csrf import CsrfViewMiddleware
    
    def check_csrf(request):
      reason = CsrfViewMiddleware().process_view(request, None, (), {})
      if reason:
        # CSRF failed
        raise PermissionException() # do what you need to do here
    

提交回复
热议问题