implementing flask_jwt_extended with templates rendering
Asked Answered
I

2

2

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']

Intracellular answered 22/3, 2019 at 9:22 Comment(2)
can you show full request(for example using curl)?Association
I'm not I understood what you meant, but the request sent to the login endpoint is sent from a simple basic form (in a HTML page).Intracellular
H
8

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

Hilariahilario answered 23/3, 2019 at 3:10 Comment(1)
Exactly what I was looking for, and indeed we are struggling with the docs about this part hope it gets updated soon.Intracellular
N
1

Also, you get same error if JWT_ACCESS_COOKIE_PATH is routed wrongly.

Nancee answered 15/9, 2020 at 10:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.