一,使用

实例化

from flask_wtf import CSRFProtect
csrf = CSRFProtect()

初始化

from flask import Flask
app = Flask(__name__)
...
WTF_CSRF_SECRET_KEY=xxx #设置token 生成salt
...
csrf.init_app(app)

csrf默认对['POST', 'PUT', 'PATCH', 'DELETE']方法进行设置、验证token机制。方法修改可以通过config中设置 WTF_CSRF_METHODS值进行更改。

如果想排除某个api不进验证,可通过csrf.exempt进行装饰。

二,实现机制

1,生成token

csrf机制通过generate_csrf()函数,生成随机数存入session同时通过随机数dump生成token,并以 csrf-token为键或config中配置的名称通过键值对的方式存在g中,在response时放在header或body中

def generate_csrf(secret_key=None, token_key=None):"""Generate a CSRF token. The token is cached for a request, so multiplecalls to this function will generate the same token.During testing, it might be useful to access the signed token in``g.csrf_token`` and the raw token in ``session['csrf_token']``.:param secret_key: Used to securely sign the token. Default is``WTF_CSRF_SECRET_KEY`` or ``SECRET_KEY``.:param token_key: Key where token is stored in session for comparision.Default is ``WTF_CSRF_FIELD_NAME`` or ``'csrf_token'``."""secret_key = _get_config(secret_key, 'WTF_CSRF_SECRET_KEY', current_app.secret_key,message='A secret key is required to use CSRF.')field_name = _get_config(token_key, 'WTF_CSRF_FIELD_NAME', 'csrf_token',message='A field name is required to use CSRF.')if field_name not in g:s = URLSafeTimedSerializer(secret_key, salt='wtf-csrf-token')if field_name not in session:session[field_name] = hashlib.sha1(os.urandom(64)).hexdigest()try:token = s.dumps(session[field_name])except TypeError:session[field_name] = hashlib.sha1(os.urandom(64)).hexdigest()token = s.dumps(session[field_name])setattr(g, field_name, token)return g.get(field_name)

2,验证token

当app接收到request, csrf会从header、form等中找csrf-token,并load后与存在session中的值进行对比验证。主要通过protect()函数实现。

def protect(self):if request.method not in current_app.config['WTF_CSRF_METHODS']:returntry:validate_csrf(self._get_csrf_token())except ValidationError as e:logger.info(e.args[0])self._error_response(e.args[0])if request.is_secure and current_app.config['WTF_CSRF_SSL_STRICT']:if not request.referrer:self._error_response('The referrer header is missing.')good_referrer = 'https://{0}/'.format(request.host)if not same_origin(request.referrer, good_referrer):self._error_response('The referrer does not match the host.')g.csrf_valid = True  # mark this request as CSRF valid

3,csrf.exempt实现机制

注册,当app启动时,对于有exempt装饰的路由(endpoint),会通过一个列表进行记录。

def exempt(self, view):"""Mark a view or blueprint to be excluded from CSRF protection.::@app.route('/some-view', methods=['POST'])@csrf.exemptdef some_view():...::bp = Blueprint(...)csrf.exempt(bp)"""if isinstance(view, Blueprint):self._exempt_blueprints.add(view.name)return viewif isinstance(view, string_types):view_location = viewelse:if isinstance(view, views.MethodViewType):view_location = '.'.join((view.__module__, view.__name__.lower()))else:view_location = '.'.join((view.__module__, view.__name__))self._exempt_views.add(view_location)return view

当路由被访问时,csrf会先检查该函数是否是exempt装饰了的路由,如果是就跳过protect()验证检查。

@app.before_requestdef csrf_protect():if not app.config['WTF_CSRF_ENABLED']:returnif not app.config['WTF_CSRF_CHECK_DEFAULT']:returnif request.method not in app.config['WTF_CSRF_METHODS']:returnif not request.endpoint:returnif request.blueprint in self._exempt_blueprints:returnview = app.view_functions.get(request.endpoint)dest = '{0}.{1}'.format(view.__module__, view.__name__)if dest in self._exempt_views:returnself.protect()

flask_wtf CSRFProtect机制相关推荐

  1. Go语言的错误异常处理机制及其应用

    一.背景 在日常编写golang程序或阅读别人的golang代码时,我们总会看到如下的一堆代码块: xx, err = func(xx) if err != nil {//do sth. to tac ...

  2. 2022-2028年中国机制砂石行业投资分析及前景预测报告

    [报告类型]产业研究 [报告价格]¥4500起 [出版时间]即时更新(交付时间约3个工作日) [发布机构]智研瞻产业研究院 [报告格式]PDF版 本报告介绍了中国机制砂石行业市场行业相关概述.中国机制 ...

  3. c#打开数据库连接池的工作机制_数据库连接池-tomcat-jdbc使用笔记

    现在 主流的数据库连接池有:Proxool.C3P0.DBCP.tomcat-jdbc.Druid.其中tomcat-jdbc是tomcat服务器比较可靠的 数据库连接池. Tomcat 在 7.0 ...

  4. python异常机制

    python异常处理机制 1.1python的内置异常 当我们在运行代码的时候一旦程序报错,就会终止运行,并且有的异常是不可避免的,但是我们可以对异常进行捕获,防止程序终止. python的内置异常是 ...

  5. 【Sql Server】数据库的安全机制

     如何实现安全机制:从以下几个方面,但主要的途径是角色和授权的方面.掌握这些便可以很好的对数据进行保护! 安全机制 客户机 网传(加密) 实例(数据库服务器限制)-服务器角色 Windows OS 验 ...

  6. 各种注意力机制PyTorch实现

    给出了整个系列的PyTorch的代码实现,以及使用方法. 各种注意力机制 Pytorch implementation of "Beyond Self-attention: External ...

  7. pytorch中调整学习率的lr_scheduler机制

    pytorch中调整学习率的lr_scheduler机制 </h1><div class="clear"></div><div class ...

  8. Pytorch 多 GPU 并行处理机制

    Pytorch 的多 GPU 处理接口是 torch.nn.DataParallel(module, device_ids),其中 module 参数是所要执行的模型,而 device_ids 则是指 ...

  9. 机器翻译注意力机制及其PyTorch实现

    前面阐述注意力理论知识,后面简单描述PyTorch利用注意力实现机器翻译 Effective Approaches to Attention-based Neural Machine Translat ...

最新文章

  1. ifelse的命令空间
  2. R符号秩检验(WILCOXON SIGNED RANK TEST)
  3. 5 个流行的用于远程工作和在线会议的开源视频会议工具
  4. Android中的资源复用小技巧
  5. windows Perl环境安装与Hello World
  6. abd.exe 需要下java吗_Abd.exe文件下载|
  7. iphone照片删掉又出现_30条让人相见恨晚的iPhone使用技巧。
  8. centos 6.3最小化安装,无法上网解决方法
  9. 干掉if-else,试试状态模式!
  10. C++Builder 2010深入TApplication类之方法
  11. 使用 Java8的 stream对list数据去重,使用filter()过滤列表,list转map
  12. 淘宝宠物用品找代理方法步骤 淘宝宠物用品店怎么开
  13. Facebook_scraper:Python获取FB用户的公开发帖【FaceBook系列 一】
  14. 黄金避险有效?量化实测黄金资产与A股轮动真实收益
  15. Android 之解析XML文件
  16. 跟着团子学SAP FICO:SAP税码传输最佳业务实践
  17. textarea剩余可输入字数
  18. [转载] 可疑的成功
  19. Spring5 Unsupported class解决方法:probably due to a new Java class file version that is supported yet
  20. Python---GPA(绩点)计算器

热门文章

  1. 3.1 计算机视觉的发展和卷积神经网络概要(百度架构师手把手带你零基础实践深度学习原版笔记系列)
  2. 一个德资企业人事经理的记录
  3. 农村生活污水处理现状分析与解决方案
  4. 数字化时代到来传统经营模式企业猝不及防
  5. java —— 统计单词数
  6. foss测试_开源研讨会探索大学中的FOSS
  7. 阿凡达云计算机,云计算中心:在云端我们也能做《阿凡达》
  8. opencv的imread函数
  9. java switch 参数不能是null
  10. 伦敦银最新价格走势图与买卖点