JWT Python 无法向用户添加令牌



我正在做一个简单的项目,我想在其中添加 jwt 身份验证。 当我登录时,我尝试创建一个新令牌,但是当我尝试查看谁是使用该令牌的用户时,它说令牌丢失。

我正在使用 Flask 和 SQLAlchemy 和 Postgresql

app.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>

您的路由受/protected 但您的JWT_ACCESS_COOKIE_PATH是/api/。这将阻止将 Cookie 发送到该终结点。将终结点更改为/api/protected,或将 cookie 路径更改为仅/

相关内容

  • 没有找到相关文章

最新更新