implementing flask_jwt_extended with templates rendering

為{幸葍}努か 提交于 2019-12-25 02:51:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!