问题
Again fighting trying to make my first flask application, this time, (after I created every I need and all works smoothly) I'm trying to protect some endpoints with flask_jwt_extended
, but I can't find how to work with them in my pages, the documentation is mostly about displaying JSON messages and some tutorials use postman while in my case I'm using HTML templates.
For example, a user sends his credentials from the login page to this endpoint :
@app.route('/login', methods=['POST'])
def UserLogin():
data = parser.parse_args()
current_user = UserModel.find_by_username(data['username'])
if not current_user:
return {'message': 'User {} doesn\'t exist'.format(data['username'])}
if UserModel.verify_hash(data['password'], current_user.password):
access_token = create_access_token(identity = data['username'])
refresh_token = create_refresh_token(identity = data['username'])
resp = jsonify({'login': True}) #I just added this line from the documentation
set_access_cookies(resp, access_token) # and this one
set_refresh_cookies(resp, refresh_token) # and this one
return redirect(url_for('results'))
else:
return {'message': 'Wrong credentials'}
and of course, I added the @jwt_required
decorator the results
endpoint:
@app.route('/result',methods = ['POST','GET'])
@jwt_required
def results():
temp={}
if request.method == 'POST':
# some code to fill temp with values
return render_template('result.html',data=temp)
So I'm getting a {
"msg": "Missing cookie \"access_token_cookie\""
}
Obviously because I'm not sending the jwt back but if send it in the return statement how can I redirect the user the page I want ??
And indeed I used app.config['JWT_TOKEN_LOCATION'] = ['cookies']
回答1:
You may want to:
resp = make_response(redirect(url_for('results')))
set_access_cookies(resp, access_token)
set_refresh_cookies(resp, refresh_token)
return resp
I don't think you need this line! --> resp = jsonify({'login': True})
Took me a while to figure it out, not sure why this part is not clear in the docs, most of the examples there just returns JSON directly
来源:https://stackoverflow.com/questions/55296439/implementing-flask-jwt-extended-with-templates-rendering