def jsonify(*args, **kwargs): if current_user.is_authenticated: if 'meta' in kwargs: kwargs['meta']['csrf_token'] = generate_csrf() else: kwargs['meta'] = {'csrf_token': generate_csrf()} return original_jsonify(*args, **kwargs)
def test_csrf_custom_token_key(self): with self.app.test_request_context(): # Generate a normal and a custom CSRF token default_csrf_token = generate_csrf() custom_csrf_token = generate_csrf(token_key='oauth_state') # Verify they are different due to using different session keys assert default_csrf_token != custom_csrf_token # However, the custom key can validate as well assert validate_csrf(custom_csrf_token, token_key='oauth_state')
def test_csrf_url_safe(self): with self.app.test_request_context(): # Generate a normal and URL safe CSRF token default_csrf_token = generate_csrf() url_safe_csrf_token = generate_csrf(url_safe=True) # Verify they are not the same and the URL one is truly URL safe assert default_csrf_token != url_safe_csrf_token assert '#' not in url_safe_csrf_token assert re.match(r'^[a-f0-9]+--[a-f0-9]+$', url_safe_csrf_token) # Verify we can validate our URL safe key assert validate_csrf(url_safe_csrf_token, url_safe=True)
def build_table_form(class_name, linked_entities): """ Returns a form with a list of entities with checkboxes""" from flask_wtf.csrf import generate_csrf from openatlas.models.entity import EntityMapper header = app.config['TABLE_HEADERS'][class_name] + [''] table = {'id': class_name, 'header': header, 'data': []} linked_ids = [entity.id for entity in linked_entities] file_stats = get_file_stats() if class_name == 'file' else None if class_name == 'file': entities = EntityMapper.get_by_system_type('file') elif class_name == 'place': entities = EntityMapper.get_by_system_type('place') else: entities = EntityMapper.get_by_codes(class_name) for entity in entities: if entity.id in linked_ids: continue # Don't show already linked entries input_ = '<input id="{id}" name="values" type="checkbox" value="{id}">'.format(id=entity.id) table['data'].append(get_base_table_data(entity, file_stats) + [input_]) if not table['data']: return uc_first(_('no entries')) return """<form class="table" method="post"> <input id="csrf_token" name="csrf_token" type="hidden" value="{token}"> {pager} <button name="form-submit" id="form-submit" type="submit">{add}</button> </form>""".format(add=uc_first(_('add')), pager=pager(table), token=generate_csrf())
def del_category(id): """Delete a category.""" try: category = project_repo.get_category(id) if category: if len(cached_cat.get_all()) > 1: ensure_authorized_to('delete', category) if request.method == 'GET': response = dict(template='admin/del_category.html', title=gettext('Delete Category'), category=category, form=dict(csrf=generate_csrf())) return handle_content_type(response) if request.method == 'POST': project_repo.delete_category(category) msg = gettext("Category deleted") flash(msg, 'success') cached_cat.reset() return redirect_content_type(url_for(".categories")) else: msg = gettext('Sorry, it is not possible to delete the only' ' available category. You can modify it, ' ' click the edit button') flash(msg, 'warning') return redirect_content_type(url_for('.categories')) else: abort(404) except HTTPException: raise except Exception as e: # pragma: no cover current_app.logger.error(e) return abort(500)
def get_authorize_url(callback_uri, **kwargs): return 'https://graph.facebook.com/oauth/authorize?' + urlencode({ 'client_id': current_app.config['FACEBOOK_CLIENT_ID'], 'redirect_uri': callback_uri, 'scope': PERMISSION_SCOPES, 'state': generate_csrf(), })
def get_authorize_url(callback_uri, **kwargs): return 'https://github.com/login/oauth/authorize?' + urlencode({ 'client_id': current_app.config['GITHUB_CLIENT_ID'], 'redirect_uri': callback_uri, 'scope': PERMISSION_SCOPES, 'state': generate_csrf(), })
def announcement(): """Manage anncounements.""" announcements = announcement_repo.get_all_announcements() response = dict(template='admin/announcement.html', title=gettext("Manage global Announcements"), announcements=announcements, csrf=generate_csrf()) return handle_content_type(response)
def test_unsubmitted_valid(self): class obj: name = 'foo' with self.app.test_request_context(): assert MyForm(obj=obj, meta={'csrf': False}).validate() t = generate_csrf() assert MyForm(obj=obj, csrf_token=t).validate()
def user_account_data(): """ Get user's account data """ return helpers.jsonify(csrf=generate_csrf(), burntAfter='2014-04-26T02:48:39+00:00', canPost=True, signedIn=False if user.is_anonymous() else True)
def csrf_token(self): request = RequestShim(self.client) environ_overrides = {} self.client.cookie_jar.inject_wsgi(environ_overrides) with self.app.test_request_context( "/accounts/login", environ_overrides=environ_overrides,): csrf_token = generate_csrf() self.app.save_session(flask.session, request) return csrf_token
def generate_csrf_token(): """Custom function for tokens generation. It returns a CSRF token with a random time limit between 60 and 180 seconds. :return A random CSRF token. """ return generate_csrf(time_limit=random.randint(60, 180))
def get_authorize_url(redirect_uri, **kwargs): csrf_token = generate_csrf() return API_AUTH_URL + '?' + urllib.parse.urlencode({ 'response_type': 'code', 'client_id': current_app.config['GOOGLE_CLIENT_ID'], 'redirect_uri': redirect_uri, 'scope': BLOGGER_SCOPE, 'state': csrf_token, 'access_type': 'offline', # necessary to get refresh token 'approval_prompt': 'force', })
def web_html(file_name): if not file_name: file_name = 'index.html' if file_name != 'favicon.ico': file_name = 'html/' + file_name # 设置csrf_token到cookie中 并会给session同步存储一份 # 读取会从session中读取 csrf_token = generate_csrf() response = make_response(current_app.send_static_file(file_name)) response.set_cookie('csrf_token', csrf_token) return response
def check_authentication(): res = {} if current_user.is_authenticated(): res.update({ 'email': current_user.email, 'username': current_user.username, 'privacy': repository.PRIVACY_CONST[current_user.global_privacy] }) res.update({ 'csrf_token': generate_csrf() }) return jsonify(res)
def index(): """ Sends the CSRF token from server to client as a cookie so that the client can scrape it out of the cookie and attach it to the X-CSRFToken header to send back to the server. http://stackoverflow.com/questions/20504846/why-is-it-common-to-put-csrf-prevention-tokens-in-cookies """ response = make_response(render_template('index.html')) response.headers.set('Set-Cookie', 'csrf_token={csrf_token}; Max-Age={max_age}'.format( csrf_token=generate_csrf(), max_age=current_app.config['WTF_CSRF_TIME_LIMIT'])) return response
def newclient(): """Endpoint for creating a new client.""" form = NewClient() if request.method == 'GET': resp = form.data resp['csrf_token'] = generate_csrf() return jsonify(resp) else: if form.validate_on_submit(): client = format_client_data(form.data) res = invoiceninja.create_client(client) return jsonify(res) else: return jsonify(form.errors)
def html_file(file_name): if not file_name: file_name = "index.html" if file_name != "favicon.ico": file_name = "html/" + file_name csrf_token = csrf.generate_csrf() response = make_response(current_app.send_static_file(file_name)) response.set_cookie("csrf_token", csrf_token) return response
def get_html_file(file_name): """提供html静态文件""" # 根据用户访问的路径提供相应的html文件 if not file_name: # 如果用户访问的是/ file_name = "index.html" if file_name != "favicon.ico": file_name = "html/" + file_name # 生产csrf_token字符串 csrf_token = generate_csrf() # 为用户设置cookie,csrf_token resp = make_response(current_app.send_static_file(file_name)) resp.set_cookie("csrf_token", csrf_token) return resp
def featured(project_id=None): """List featured projects of PYBOSSA.""" try: if request.method == 'GET': categories = cached_cat.get_all() projects = {} for c in categories: n_projects = cached_projects.n_count(category=c.short_name) projects[c.short_name] = cached_projects.get( category=c.short_name, page=1, per_page=n_projects) response = dict(template = '/admin/projects.html', projects=projects, categories=categories, form=dict(csrf=generate_csrf())) return handle_content_type(response) else: project = project_repo.get(project_id) if project: ensure_authorized_to('update', project) if request.method == 'POST': if project.featured is True: msg = "Project.id %s already featured" % project_id return format_error(msg, 415) cached_projects.reset() project.featured = True project_repo.update(project) return json.dumps(project.dictize()) if request.method == 'DELETE': if project.featured is False: msg = 'Project.id %s is not featured' % project_id return format_error(msg, 415) cached_projects.reset() project.featured = False project_repo.update(project) return json.dumps(project.dictize()) else: msg = 'Project.id %s not found' % project_id return format_error(msg, 404) except Exception as e: # pragma: no cover current_app.logger.error(e) return abort(500)
def csrf_token(self): # First, we'll wrap our request shim around the test client, so that # it will work correctly when Flask asks it to set a cookie. request = RequestShim(self) # Next, we need to look up any cookies that might already exist on # this test client, such as the secure cookie that powers `flask.session`, # and make a test request context that has those cookies in it. environ_overrides = {} self.cookie_jar.inject_wsgi(environ_overrides) with flask.current_app.test_request_context( "/login", environ_overrides=environ_overrides, ): # Now, we call Flask-WTF's method of generating a CSRF token... csrf_token = generate_csrf() # ...which also sets a value in `flask.session`, so we need to # ask Flask to save that value to the cookie jar in the test # client. This is where we actually use that request shim we made! flask.current_app.save_session(flask.session, request) # And finally, return that CSRF token we got from Flask-WTF. return csrf_token
def newinvoice(): """Endpoint for creating a new invoice.""" form = NewInvoice() if request.method == 'GET': resp = form.data resp['csrf_token'] = generate_csrf() return jsonify(resp) else: invoice = request.get_json() invoice = format_invoice_data(invoice) if (not invoice.get('message') and not invoice.get('cause')): if (invoice.get('recurring') is not None and invoice.get('recurring') != ''): if invoice.get('email_invoice'): del invoice['email_invoice'] res = invoiceninja.create_recurring_invoice(invoice) else: res = invoiceninja.create_invoice(invoice) return jsonify(res) error = dict(message=invoice['message']) return jsonify(error)
def reset_api_key(name): """ Reset API-KEY for user. Returns a Jinja2 template. """ if request.method == 'POST': user = user_repo.get_by_name(name) if not user: return abort(404) ensure_authorized_to('update', user) user.api_key = model.make_uuid() user_repo.update(user) cached_users.delete_user_summary(user.name) msg = gettext('New API-KEY generated') flash(msg, 'success') return redirect_content_type(url_for('account.profile', name=name)) else: csrf = dict(form=dict(csrf=generate_csrf())) return jsonify(csrf)
def get_html(get_file_name): ''' :param file_name: :return: static_html ''' # 127.0.0.1:5000/ -> 127.0.0.1:5000/index.html if not get_file_name: get_file_name = 'index.html' # 127.0.0.1:5000/~.html if get_file_name != 'favicon.ico': get_file_name = 'html/' + get_file_name # 生成csrf_token csrf_token = csrf.generate_csrf() resp = current_app.send_static_file(get_file_name) #设置csrf_token resp.set_cookie('csrf_token', csrf_token) return resp
def csrf_token(self): # First, we'll wrap our request shim around the test client, so that # it will work correctly when Flask asks it to set a cookie. request = RequestShim(self) # Next, we need to look up any cookies that might already exist on # this test client, such as the secure cookie that powers # `flask.session`, and make a test request context that has # those cookies in it. environ_overrides = {} self.cookie_jar.inject_wsgi(environ_overrides) with flask.current_app.test_request_context( "/accounts/login", environ_overrides=environ_overrides, ): # Now, we call Flask-WTF's method of generating a CSRF token... csrf_token = generate_csrf() # ...which also sets a value in `flask.session`, so we need to # ask Flask to save that value to the cookie jar in the test # client. This is where we actually use that request shim we made! flask.current_app.save_session(flask.session, request) # And finally, return that CSRF token we got from Flask-WTF. return csrf_token
def csrf_refresh( subdomain: Optional[str] = None, ) -> Tuple[Dict[str, Any], int, Dict[str, str]]: # TODO: Need ReturnRenderWith here """Serve a refreshed CSRF token to ensure HTML forms never expire.""" parsed_host = urlparse(request.url_root) origin = parsed_host.scheme + '://' + parsed_host.netloc if 'Origin' in request.headers: # Origin is present in (a) cross-site requests and (b) same site requests in # some browsers. Therefore, if Origin is present, confirm it matches our domain. if request.headers['Origin'] != origin: abort(403) return ( {'csrf_token': generate_csrf()}, 200, { 'Access-Control-Allow-Origin': origin, 'Vary': 'Origin', 'Expires': (request_timestamp() + timedelta(minutes=10)).strftime( '%a, %d %b %Y %H:%M:%S GMT' ), }, )
def restore_csrf(): return {'csrf_token': generate_csrf()} # @app.route('/login', methods=['GET', 'POST']) # def login(): # if not request.is_json: # return jsonify({"msg": "Missing JSON in request"}), 400 # username = request.json.get('username', None) # password = request.json.get('password', None) # if not username or not password: # return {"errors": ["Missing required parameters"]}, 400 # authenticated, user = User.authenticate(username, password) # print(authenticated) # print(user) # if authenticated: # login_user(user) # return {"current_user_id": current_user.id} # return {"errors": ["Invalid username or password"]}, 401
def get_html(html_file_name): ''' 提供html文件 :param html_file_name: url中文件名字 :return: ''' # 如果html_file_name为" ", 表示访问的路径是/, 请求主页 if not html_file_name: html_file_name = 'index.html' if html_file_name != 'favicon.ico': html_file_name = 'html/' + html_file_name # 创建一个csrf_token值 csrf_token = generate_csrf() # flask提供返回静态文件的方法 resp = make_response(current_app.send_static_file(html_file_name)) # 设置cookie,本次浏览有效 resp.set_cookie('csrf_token', csrf_token) return resp
def get_html_file(file_name): """提供html文件""" # 根据用户访问的路径指明的html文件名file_name,提供相对应的html文件 if not file_name: #表示用户访问的是/ file_name = "index.html" if file_name != "favicon.ico": file_name = "html/" + file_name # 使用wtf生成随机的csrf_token的字符串 csrf_token = generate_csrf() #为用户设置cookie csrf_token resp = make_response(current_app.send_static_file(file_name)) resp.set_cookie("csrf_token",csrf_token) # resp = current_app.send_static_file(file_name) return resp
def csrf_token(self) -> Response: """ Return the csrf token --- get: description: >- Fetch the CSRF token responses: 200: description: Result contains the CSRF token content: application/json: schema: type: object properties: result: type: string 401: $ref: '#/components/responses/401' 500: $ref: '#/components/responses/500' """ return self.response(200, result=generate_csrf())
def del_category(id): """Delete a category.""" try: category = project_repo.get_category(id) if category: if len(cached_cat.get_all()) > 1: ensure_authorized_to('delete', category) if request.method == 'GET': response = dict(template='admin/del_category.html', title=gettext('Delete Category'), category=category, form=dict(csrf=generate_csrf())) return handle_content_type(response) if request.method == 'POST': project_repo.delete_category(category) msg = gettext("Category deleted") flash(msg, 'success') cached_cat.reset() return redirect_content_type(url_for(".categories")) else: msg = gettext('Sorry, it is not possible to delete the only' ' available category. You can modify it, ' ' click the edit button') flash(msg, 'warning') return redirect_content_type(url_for('.categories')) else: abort(404) except IntegrityError: msg = gettext('Sorry, it is not possible to delete a category' ' if there are projects assigned to it.') flash(msg, 'error') return redirect_content_type(url_for('.categories')) except HTTPException: raise except Exception as e: # pragma: no cover current_app.logger.error(e) return abort(500)
def base_render_json( form, include_user=True, include_auth_token=False, additional=None, error_status_code=400, ): has_errors = len(form.errors) > 0 user = form.user if hasattr(form, "user") else None if has_errors: code = error_status_code payload = json_error_response(errors=form.errors) else: code = 200 payload = dict() if user: # This allows anonymous GETs via JSON if include_user: payload["user"] = user.get_security_payload() if include_auth_token: # view wants to return auth_token - check behavior config if ( config_value("BACKWARDS_COMPAT_AUTH_TOKEN") or "include_auth_token" in request.args ): token = user.get_auth_token() payload["user"]["authentication_token"] = token # Return csrf_token on each JSON response - just as every form # has it rendered. payload["csrf_token"] = csrf.generate_csrf() if additional: payload.update(additional) return _security._render_json(payload, code, headers=None, user=user)
def first_request(): """首次Get请求下发CSRF-TOKEN以及相关cookies数据 :return: json格式字符串 """ # response = response() # 调用函数生成 csrf_token; generate_csrf()里面在包里的session.py中 # hashlib.sha1(os.urandom(64)).hexdigest() # s = URLSafeTimedSerializer(secret_key, salt='wtf-csrf-token') csrf_token = generate_csrf() # 通过 cookie 将值传给前端 result = {"code": 0, 'msg': 'success'} resp = make_response(jsonify(result)) # 指定cookie放在/位置 resp.set_cookie("csrf_token", csrf_token, httponly=False, path='/') resp.set_cookie('datetime', getlocaltime()) # 允许前端可以通过获取header的字段 resp.headers['Access-Control-Expose-Headers'] = 'csrf_token,Set-Cookie' resp.headers['csrf_token'] = csrf_token resp.headers['supportsCredentials'] = True resp.headers['Access-Control-Allow-Origin'] = '*' # resp.headers['Access-Control-Allow-Credentials'] = True return resp
def home(): if not current_user.is_authenticated: return redirect('https://www.trot.to' if request.host == 'trot.to' else '/_/auth/login') from modules.organizations.helpers import get_org_settings template = JINJA_ENVIRONMENT.get_template('index.html') namespaces = config.get_organization_config(current_user.organization).get( 'namespaces', []) admin_links = get_org_settings(current_user.organization).get( 'admin_links', []) return template.render({ 'csrf_token': generate_csrf(), 'default_namespace': config.get_default_namespace(current_user.organization), 'namespaces': json.dumps(namespaces), 'admin_links': json.dumps(admin_links) })
def add_word(): if request.method == "GET": return {"csrf_token": generate_csrf()} data = request.get_json() words = clean_input(data["words"]) group_name = data["group"] group = Group.query.filter_by(name=group_name).first() if not current_user.is_authenticated or len(words) == 0: return "User not authenticated", 405 if group is None: return "Wrong group.", 400 if group.name not in current_user.group_names(): return "Not allowed", 405 added_words = [] for w in words: if validate_word(w) and not Word.query.filter_by( group_id=group.id).filter_by(word=w).first(): added_words.append(w) word = Word(word=w, user_id=current_user.get_id(), group_id=group.id) db.session.add(word) db.session.commit() if len(added_words) == 0: return "No words added.", 400 return {"added_words": added_words, "count": len(added_words)}
def get_html(html_file_name): """ 提供html文件 :return: """ # 如果html_file_name为"",表示访问路径是 / if not html_file_name: html_file_name = "index.html" # 如果资源名不是favicon.ico if html_file_name != "favicon.ico": html_file_name = "html/" + html_file_name # 创建一个csrf_token值 csrf_token = csrf.generate_csrf() # flask提供的返回静态文件的方法 # make_response:生成响应对象的方法 resp = make_response(current_app.send_static_file(html_file_name)) # 设置cookie值 resp.set_cookie("csrf_token", csrf_token) return resp
def asset(bendungan_id): bend = Bendungan.query.get(bendungan_id) assets = Asset.query.filter(Asset.bendungan_id == bend.id).all() kerusakan = Kerusakan.query.filter(Kerusakan.bendungan_id == bend.id).all() ass = [] rusak = [] for ker in kerusakan: if ker.asset_id not in rusak: rusak.append(ker.asset_id) for asset in assets: ass.append({ 'id': asset.id, 'asset': asset, 'status': asset.id in rusak }) return render_template('kinerja/asset.html', name=bend.name, bend_id=bend.id, assets=ass, csrf=generate_csrf(), kategori=komponen)
def csrf_refresh(subdomain=None): parsed_host = urlparse(request.url_root) origin = parsed_host.scheme + '://' + parsed_host.netloc if 'Origin' in request.headers: # Origin is present in (a) cross-site requests and (b) same site requests in some browsers. # Therefore, if Origin is present, confirm it matches our domain. if request.headers['Origin'] != origin: abort(403) return ( { 'csrf_token': generate_csrf() }, 200, { 'Access-Control-Allow-Origin': origin, 'Vary': 'Origin', 'Expires': (request_timestamp() + timedelta(minutes=10)).strftime('%a, %d %b %Y %H:%M:%S GMT'), }, )
def get_html_file(file_name): #print(file_name) # 1. 处理没有文件名, 自行拼接首页 if not file_name: file_name = 'index.html' # 2. 如果发现文件名不叫"favicon.ico", 再拼接html/路径 # favicon.ico: 浏览器为了显示图标, 会自动向地址发出一个请求 if file_name != 'favicon.ico': file_name = 'html/' + file_name print(file_name) # 将html当做静态文件返回 # 3. 如果文件名是'favicon.ico', 就直接返回 # return current_app.send_static_file(file_name) # generate_csrf会检测当前session, 如果有, 则返回session中的. 如果没有, 则重新创建 # generate_csrf的作用是新建session (随机生成一个token值) csrf_token = generate_csrf() response = make_response(current_app.send_static_file(file_name)) response.set_cookie('csrf_token', csrf_token) return response
def akter_request(response): csrf_token = generate_csrf() response.set_cookie("csrf_token", csrf_token) return response
def after_request(response): csrf_token = csrf.generate_csrf() response.set_cookie('csrf_token', csrf_token) return response
def csrf_cookie_handler(response): """Called at end of every request. Uses session to track state (set/clear) Ideally we just need to set this once - however by default Flask-WTF has a time-out on these tokens governed by *WTF_CSRF_TIME_LIMIT*. While we could set that to None - and OWASP implies this is fine - that might not be agreeable to everyone. So as a basic usability hack - we check if it is expired and re-generate so at least the user doesn't have to log out and back in (just refresh). We also support a *CSRF_COOKIE_REFRESH_EACH_REQUEST* analogous to Flask's *SESSION_REFRESH_EACH_REQUEST* It is of course removed on logout/session end. Other info on web suggests replacing on every POST and accepting up to 'age' ago. """ csrf_cookie = config_value("CSRF_COOKIE") if not csrf_cookie or not csrf_cookie["key"]: return response op = session.get("fs_cc", None) if not op: remember_cookie_name = current_app.config.get( "REMEMBER_COOKIE_NAME", REMEMBER_COOKIE_NAME ) has_remember_cookie = ( remember_cookie_name in request.cookies and session.get("remember") != "clear" ) # Set cookie if successfully logged in with flask_login's remember cookie if has_remember_cookie and current_user.is_authenticated: op = "set" else: return response if op == "clear": response.delete_cookie( csrf_cookie["key"], path=csrf_cookie.get("path", "/"), domain=csrf_cookie.get("domain", None), ) session.pop("fs_cc") return response # Send a cookie if any of: # 1) CSRF_COOKIE_REFRESH_EACH_REQUEST is true # 2) fs_cc == "set" - this is on first login # 3) existing cookie has expired send = False if op == "set": send = True session["fs_cc"] = "sent" elif config_value("CSRF_COOKIE_REFRESH_EACH_REQUEST"): send = True elif current_app.config["WTF_CSRF_TIME_LIMIT"]: current_cookie = request.cookies.get(csrf_cookie["key"], None) if current_cookie: # Lets make sure it isn't expired if app doesn't set TIME_LIMIT to None. try: csrf.validate_csrf(current_cookie) except ValidationError: send = True if send: kwargs = {k: v for k, v in csrf_cookie.items()} kwargs.pop("key") kwargs["value"] = csrf.generate_csrf() response.set_cookie(csrf_cookie["key"], **kwargs) return response
def after(response): response.set_cookie('XSRF-COOKIE', generate_csrf()) return response
def get_csrf_token(): return generate_csrf()
def test_validate_csrf(self): with self.app.test_request_context(): self.assertRaises(ValidationError, validate_csrf, None) self.assertRaises(ValidationError, validate_csrf, 'invalid') validate_csrf(generate_csrf())
def form_to_json(form): """Return a form in JSON format.""" tmp = form.data tmp['errors'] = form.errors tmp['csrf'] = generate_csrf() return tmp
def test_validate_not_expiring_csrf(self): with self.app.test_request_context(): csrf_token = generate_csrf(time_limit=False) assert validate_csrf(csrf_token, time_limit=False)
def test_validate_csrf(self): with self.app.test_request_context(): assert not validate_csrf('ff##dd') csrf_token = generate_csrf() assert validate_csrf(csrf_token)
def gen_csrf(cls): """ return a csrf token """ return '%s' % generate_csrf()
def setup_csrftoken(response): #生成 csrf_token的值 csrf_token = generate_csrf() response.set_cookie('csrf_token', csrf_token) return response
def setup_csrf(response): response.set_cookie('csrf_token', generate_csrf()) return response
def after_request(resp): #设置csrf_token csrf_token = generate_csrf() resp.set_cookie("csrf_token",csrf_token) return resp
def after_request(response): # 1.生成csrf_token csrf_token = csrf.generate_csrf() #2. 将csrf_token写入到浏览器 response.set_cookie('csrf_token', csrf_token) return response
def csrf_token(): return csrf.generate_csrf()
def get_csrf_headers(): # Instantiating a Form makes sure there's a CSRF token available # Generate a CSRF token put an hmac key in the session. return {"X-CSRF-Token": generate_csrf()}
def session_info(): user = current_app.user_datastore.get_user(session['user_id']) data = user.get_security_payload() data['csrf_token'] = generate_csrf() return jsonify(data)
def after_request(response): # 调用函数生成 csrf_token csrf_token = generate_csrf() # 通过 cookie 将值传给前端 response.set_cookie("csrf_token", csrf_token) return response
def inject_csrf_token(response): response.headers.set('X-CSRF-Token', generate_csrf()) return response