我是编码新手。Flask
我在using中设置了登录功能flask-JWT
。到目前为止,我能够登录(在“/login”上)并使用jwt
.
但是,我还有其他使用包装器(@token_required)保护的路由。我想让它一旦用户登录,令牌将被传递到其他受保护的页面,然后他们将能够访问这些页面。
这些是我的代码:
保护页面的包装器
def token_required(f): #wrapper for token auth
@wraps(f)
def decorated(*args, **kwargs):
token = request.args.get('token')
if 'x-access-token' in request.headers:
token = request.headers['x-access-token']
if not token:
return jsonify({'message': 'Token is missing!'}), 401
try:
data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])
current_u = User.query.filter_by(username=data['user']).first()
#identify user, otherwise, return error
except:
return jsonify({'message': 'Token is invalid!'}), 401
return f(current_u, *args, **kwargs) #previously return f(*args, **kwargs)
return decorated
登录路径
@app.route('/login', methods=['GET', 'POST']) #login route
def login():
auth = request.authorization
if not auth or not auth.username or not auth.password:
return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm = "Login Required!"'})
user = User.query.filter_by(username=auth.username).first()
if not user:
return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm = "Login Required!"'})
if user.check_password(auth.password):
token = jwt.encode({'user': auth.username, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=2)}, app.config['SECRET_KEY'])
return jsonify({'message': 'hello ' + user.username}, {'token': token})
return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm = "Login Required!"'})
使用包装器的受保护路由
@app.route('/protected') #protected routes
@token_required
def protected(current_u):
return jsonify({'message' : 'This is only for people with valid tokens'})
我只是停留在这个时间点,因为我找不到专门针对此的教程/也许这也是一个不知道要搜索什么的问题。有人可以帮我吗?