我有一个flask站点,我使用flask的内置开发服务器(本地机器)在本地运行。在我提供页面之前,我正在运行自定义安全评估功能,以确保用户有权访问该页面。如果用户无权访问该页面,我会尝试将用户重定向回主页。除了重定向之外,此工作流中的一切都按预期进行。即使“重定向”调用仍在执行,用户也可以像拥有完全授权一样获得页面服务。我很可能错误地使用了重定向功能——请赐教。这是烧瓶站点设置:from flask import Flask, render_template, request, url_for, redirect, Markup, session, abortdef security(page_name): # Direct not logged in users to the login form if not session.get('logged_in'): return render_template('login.html') else: try: # Update user's permissions permissions_list = login_helpers.get_user_permissions_by_id(user_id) session['permissions'] = permissions_list if requested_page_abbreviation not in session['permissions']: # User does not have access -- bounce user back to home # I see this appear in the console print('Not authorized') # This must get executed, but the user does not get directed back home -- instead the resulting page loads as if the user has permissions return redirect('/home') # This does not execute # If I replace this line above the "return redirect('/home')" call, the expected "Unauthorized" page results and the 401 HTTP code is returned abort(401) except KeyError: # User has not yet had permissions set -- bounce user back to home to login return redirect(url_for('home'))@app.route('/', methods=['GET','POST'])def home(): return render_template('home.html')@app.route('/test_page', methods=['POST'])def test_page(): security_check('TEST') return render_template('test_page.html')
2 回答
宝慕林4294392
TA贡献2021条经验 获得超8个赞
我有类似的程序,但我没有从安全检查助手方法重定向。
我正在做的是:我有一种方法可以检查安全性并根据凭据返回真/假。获得安全检查结果后,我从我的路由定义方法重定向。没有来自辅助方法的重定向。
我的代码示例如下,它对我有用:
@app.route("/", methods=['GET', 'POST'])
def mymethod():
secure = sec()
if(secure):
return "Secure page"
else:
return redirect('/login')
@app.route("/login", methods=['GET', 'POST'])
def login():
return "login page"
# Do not redirect from your helper method
def sec():
secured = False
# Your security logic and code
if secured:
return True
else:
return False
你会注意到我的安全检查器只是检查有效性并告诉我该怎么做。您可以根据您的路线要求从路线中删除 GET 或 POST,我只是将两者都放在那里。
添加回答
举报
0/150
提交
取消