我正在做一个简单的项目,我想在其中添加 jwt 身份验证。当我登录时,我尝试创建一个新令牌,但是当我试图查看谁是使用该令牌的用户时,它说该令牌丢失了。
我在 Postgresql 中使用 Flask 和 SQLAlchemy
应用程序.py
app.config['JWT_TOKEN_LOCATION'] = ['cookies']
#app.config['JWT_COOKIE_SECURE'] = False
app.config['JWT_ACCESS_COOKIE_PATH'] = '/api/'
app.config['JWT_REFRESH_COOKIE_PATH'] = '/token/refresh'
app.config['JWT_COOKIE_CSRF_PROTECT'] = False
app.config['JWT_SECRET_KEY'] = 'abva'
jwt = JWTManager(app)
@app.route('/token/auth', methods=['POST'])
def login():
email = request.form['email']
password = request.form['password']
user = User.query.all()
for user in user:
if user.email == email and user.password == password:
access_token = create_access_token(identity=user.email)
refresh_token = create_refresh_token(identity=user.email)
# Set the JWTs and the CSRF double submit protection cookies
# in this response
resp = jsonify({'login': True})
set_access_cookies(resp, access_token)
set_refresh_cookies(resp, refresh_token)
return resp, 200
return jsonify({'login': False}), 401
@app.route('/protected', methods=['GET'])
@jwt_required
def protected():
ret = {
'current_identity': get_jwt_identity(), # test
}
return jsonify(ret), 200
@app.route('/token/remove', methods=['POST'])
def logout():
resp = jsonify({'logout': True})
unset_jwt_cookies(resp)
return resp, 200
@jwt.user_identity_loader
def user_identity_lookup(user):
return user
add_user.html
<!DOCTYPE html>
<html>
<body>
<form method="POST" action="/token/auth">
<label> Email: </label>
<input id="email" name ="email" type="text" />
<label> Password: </label>
<input id="password" name ="password" type="password" />
<input type="submit" />
</form>
<form method="POST" action="/token/remove">
<input type="submit" value="LogOut" />
</form>
</body>
</html>