In Flask how can I use the secure session to authenticate user with curl?
curl, flask, python, rest
Solution
The response to your login request will contain a `Set-Cookie` header looking something like this:
Set-Cookie:session=<encoded session>; Path=/; HttpOnly
You need to send that cookie with your curl request so that the session data is available for processing, you can add additional headers to curl requests with `-H`, or specify the cookie explicitly:
curl --cookie "session=<encoded session>" http://localhost:5000/address/
Browsers will handle this for you of course, but curl is totally stateless and wont parse and store the `Set-Cookie` header for you by default, though if you're performing the login using curl, you can tell it to store the cookie in a cookie jar with `-c <file>`, and then you can read from it on your next request with `-b file`
HTTP Cookie wiki page
Curl cookie docs
Curl man page
Problem
I am building a RESTful application with Flask which will use sessions to track the logged in user. Here is the login code which I adapted from this Flask tutorial ``` @mod.route('/login/', methods=['GET', 'POST']) def login(): user = User.query.filter_by(email=request.json['email']).first() # we use werkzeug to validate user's password if user and check_password_hash(user.password, request.json['password']): # the session can't be modified as it's signed, # it's a safe place to store the user id session['user_id'] = user.id resp = jsonify({'status':'authenticated'}) else: resp = jsonify({'status':'Invalid usernam/password'}) resp.status_code = 401 return resp ``` When a user first logs in, I store their userid in the session, so that when the same user requests a resource, the data is tailored to them: ``` @mod.route('/address/') @requires_login def user_data(): user = User.query.filter_by(id=session['usr_id']).first resp = jsonify(user.address) return resp ``` If I issue this command after logging in: ``` curl http://localhost:5000/address/ ``` I receive: ``` {"status": 401, "message": "Unauthorized"} ``` instead of the address information for my logged in user. Can anyone tell me how I can use the session in subsequent curl calls to return data that is specific to the userid stored in the cookie?