我们从Python开源项目中,提取了以下25个代码示例,用于说明如何使用flask.request.csrf_valid()。
def protect(self): if request.method not in self._app.config['WTF_CSRF_METHODS']: return if not validate_csrf(self._get_csrf_token()): reason = 'CSRF token missing or incorrect.' return self._error_response(reason) if request.is_secure and self._app.config['WTF_CSRF_SSL_STRICT']: if not request.referrer: reason = 'Referrer checking failed - no Referrer.' return self._error_response(reason) good_referrer = 'https://%s/' % request.host if not same_origin(request.referrer, good_referrer): reason = 'Referrer checking failed - origin does not match.' return self._error_response(reason) request.csrf_valid = True # mark this request is csrf valid
def validate_csrf_token(self, field): if not self.csrf_enabled: return True if hasattr(request, 'csrf_valid') and request.csrf_valid: # this is validated by CsrfProtect return True if not validate_csrf(field.data, self.SECRET_KEY, self.TIME_LIMIT): raise ValidationError(field.gettext('CSRF token missing'))
def init_app(self, app): app.jinja_env.globals['csrf_token'] = generate_csrf strict = app.config.get('WTF_CSRF_SSL_STRICT', True) csrf_enabled = app.config.get('WTF_CSRF_ENABLED', True) @app.before_request def _csrf_protect(): # many things come from django.middleware.csrf if not csrf_enabled: return if request.method in ('GET', 'HEAD', 'OPTIONS', 'TRACE'): return if self._exempt_views: if not request.endpoint: return view = app.view_functions.get(request.endpoint) if not view: return dest = '%s.%s' % (view.__module__, view.__name__) if dest in self._exempt_views: return csrf_token = None if request.method in ('POST', 'PUT', 'PATCH'): # find the ``csrf_token`` field in the subitted form # if the form had a prefix, the name will be ``{prefix}-csrf_token`` for key in request.form: if key.endswith('csrf_token'): csrf_token = request.form[key] if not csrf_token: # You can get csrf token from header # The header name is the same as Django csrf_token = request.headers.get('X-CSRFToken') if not csrf_token: # The header name is the same as Rails csrf_token = request.headers.get('X-CSRF-Token') if not validate_csrf(csrf_token): reason = 'CSRF token missing or incorrect.' return self._error_response(reason) if request.is_secure and strict: if not request.referrer: reason = 'Referrer checking failed - no Referrer.' return self._error_response(reason) good_referrer = 'https://%s/' % request.host if not same_origin(request.referrer, good_referrer): reason = 'Referrer checking failed - origin not match.' return self._error_response(reason) request.csrf_valid = True # mark this request is csrf valid