我正在一个单独的服务的帮助下生成一个身份验证令牌。我在一些服务的帮助下生成身份验证令牌。我在login
路线中生成令牌。如何在生成登录令牌之前阻止访问其他路由,以及如何在其他路由中访问该令牌?
@app.route('/login', methods=['GET', 'POST'])
def login():
error=None
if request.method=='POST':
if request.form['username']!='admin' or request.form['password']!='1234':
error ='Invalid Credentials. Please try again.'
else:
username=request.form['username']
password=request.form['password']
auth_url='http://192.168.206.133:5000/v2.0'
token = generateToken(username=username, password=password, auth_url=auth_url)
return redirect(url_for('getstats'))
return render_template('login.html', error=error)
# this route should require and use the auth token
@app.route('/metering')
def getstats():
return render_template('metering.html')
答案 0 :(得分:2)
因此,您似乎正在尝试访问不同路由中的令牌。
我建议将它们存储在会话中。为此,请务必从session
flask
导入from flask import session
变量。
您想在session.
中设置令牌的值现在,我会使用auth_token
作为会话字段,但您可以使用您想要的任何内容:
@app.route('/login', methods=['GET', 'POST'])
def login():
error=None
if request.method=='POST':
if request.form['username']!='admin' or request.form['password']!='1234':
error ='Invalid Credentials. Please try again.'
else:
username=request.form['username']
password=request.form['password']
auth_url='http://192.168.206.133:5000/v2.0'
token = generateToken(username=username, password=password, auth_url=auth_url)
session["auth_token"] = token # store the token in the session here
session["authenticated"] = True
return redirect(url_for('getstats'))
return render_template('login.html', error=error)
from functools import wraps
def authenticated_resource(function):
@wraps(function)
def decorated(*args, **kwargs):
if session.get("authenticated"):
return function(*args, **kwargs)
return redirect(url_for("login"))
return decorated
然后,访问令牌:
@app.route('/metering')
@authenticated_resource
def getstats():
token = session.get("auth_token")
# you might want to verify that the token was in the session, as such
if token:
return render_template('metering.html')
else:
abort(403)
注意:要使用abort
,您还需要从flask
导入该内容。