Skip to content

Latest commit

 

History

History
42 lines (26 loc) · 1023 Bytes

面试题007.md

File metadata and controls

42 lines (26 loc) · 1023 Bytes

面试题007:

一、CSRF是什么?django中如何防护?

1.开启csrf

Cross-site request forgery (CSRF) is an attack that tricks a user into making unwanted actions on a website, where they are already authenticated, while they are visiting another site.

  • 全局开启csrf防护
# 全局开启csrf防护
django.middleware.csrf.CsrfViewMiddleware	# 生成csrf cookie和判断csrf token是否正确
  • 针对某一个函数视图开启csrf防护

    @csrf_protect
    def my_view(request):
        # 函数视图逻辑
        return render(request, "example.html")
  • 针对某一个类视图开启csrf防护

    @method_decorator(csrf_protect)
    class MyClassView(request):
        # 类视图逻辑
        return render(request, "example.html")
  • 在template模版中,使用{% csrf_token %},去生成随机的csrf token(key为csrfmiddlewaretoken的隐藏字段)

2.关闭csrf

注释掉CsrfViewMiddleware中间件,添加csrf_exempt装饰器