thongn98
thongn98

Reputation: 11

Previously-set request cookies returns None in a Flask application

I'm trying to store JWT Tokens in cookies for a Flask application to restrict some endpoints. An endpoint, "/authorize" , is responsible for setting the cookies then redirect the page to the root endpoint, "/".

from flask      import Flask, request, make_response, redirect

@app.route("/authorize", methods=["GET"])
def authorize():
   token       = request.args.get('token')
   expires     = request.args.get('expires')

   # some code to validate the token

   resp_output = make_response(redirect("/"))
   resp_output.set_cookie("token", token, expires=expires)

   return resp_output

@app.route("/", methods=["GET"])
def index():
   token = request.cookies.get("token)

   # do something with the token 

However, when I tried to deploy this, I ran into some problems with the redirecting and therefore have to change redirect("/") to redirect("https://someaddress.com/)" where https://someaddress.com/ is the address of the flask application. Now when I try to retrieve the token cookies in the root endpoint, it returns None. I suspect it is because the redirection has turnt from an internal one to an external one.

Please help me find a workaround for this. Or if you think I should resolve the problems that lead to the change from internal to external redirection so I can go back to what works. (If anyone can point me to some resources explaining exactly how redirection, or more specifically Flask's redirection, works, I'd really appreciate it.)

Upvotes: 1

Views: 360

Answers (1)

Kenny Aires
Kenny Aires

Reputation: 1438

Using url_for function from flask should work in your case, as it will look for the link within the app context:

from flask import Flask, request, make_response, redirect, url_for

@app.route("/authorize", methods=["GET"])
def authorize():
   token = request.args.get('token')
   expires = request.args.get('expires')

   # some code to validate the token

   resp_output = make_response(redirect(url_for('index')))
   resp_output.set_cookie("token", token, expires=expires)

   return resp_output

@app.route("/", methods=["GET"])
def index():
   token = request.cookies.get("token)

   # do something with the token

Btw, I would recommend you pass your authorization logic to a decorator, have a look on authorization decorators using flask.

In case this don't work in production, that can be some setting related to your reverse proxy - like nginx conf file. Let me know if it is the case

on Nginx file on sites-enabled folder etc/nginx/sites-enabled/<project-name>, comment or remove the following line:

proxy_set_header   Host                 $host;

Hope it suits you well!

Upvotes: 1

Related Questions