How to read cookies not set by Flask

2019-08-11 09:47发布

问题:

I have a Flask site that runs inside an iframe of a wordpress site.

Both sites are on the same domain. That is, the wordpress site is on something like www.example.com and Flask site is on api.example.com.

I need to show some user specific stuff in the iframe. So how do I read a cookie that was set by wordpress in Flask? Or check if it is set? Basically, I want to know if the user is logged in or not (session cookie present) and their username.

The best would be if I could somehow integrate the Flask-Login plugin with the actual Wordpress login, however, I do not expect that to be possible.

回答1:

When a cookie is created its domain is set. You need to ensure that the domain is set so that both sites domain match the cookie domain. For example example.com will allow the cookies to be viewed by both sites or put another way they will be set along with the request to both servers.

The wordpress login can be integrated with Flask. You will need to extract the session id/cookie contents and then make a request to the wordpress site.

Flask Code:

request.cookies.get('username')  # get single cookie
request.cookies  # get all as dict

Cookie attribute

This requests check if the session is valid and returns the user credentials. If it succeeds - meaning the user can be automatically logged in - you then invoke cookies

Note: You will have to synchronize the sessions manually. When a session is created on the api side it will continue to exist until it expires or you manually call logout. Also if you log out of the wordpress side the flask session will continue to exist

More info on cookies