I'm trying to use Gmail API to access emails with Flask-Authlib. after user authorization, the server will put a access token in session, then it will direct to a react route /test
. in the react component invoked by /test
, it will send a GET
request to another method in backend for email info, however, the access token doesnt exist anymore although i set session life time to be long enough.
So the flow is like this: login -> authorized(return to front end) -> send Get request to backend /index
.
Any help would be appreciated.
server:
@app.route('/index')
def index():
print(get_access_token()) # does not work
if 'access_token' in session:
me = gmail.get('userinfo')
user_id = me.data['id']
access_token = get_access_token()
start = time.time()
inbox = Inbox(gmail, access_token, user_id)
emails = inbox.emails
end = time.time()
return jsonify({
"emails": emails,
'me': user_id,
'count': len(emails),
'time': end - start,
'request time': inbox.request_time
})
return jsonify({
'status': 403,
'session': session.get('access_token')
})
@app.route('/login')
def login():
return gmail.authorize(callback=url_for('authorized', _external=True))
@app.route('/logout')
def logout():
session.pop('access_token', None)
return redirect(url_for('index'))
@app.route('/authorized')
def authorized():
resp = gmail.authorized_response()
if resp is None:
return 'Access denied: reason={} error={}'.format(
request.args['error_reason'],
request.args['error_description']
)
session['access_token'] = (resp['access_token'], '')
print(get_access_token()) # works
return redirect('test')
@gmail.tokengetter
def get_access_token():
return session.get('access_token')
client:
const Test = React.createClass({
componentDidMount() {
fetch('/index')
.then(response => {
return response.json()
})
.then(json => {
console.log(json)
})
.catch(ex => {
console.log(ex)
})
},
render() {
return (
<div>
tsetdsfadsf
</div>
)
}
})
render((
<Router history={history}>
<Route component={App}>
<Route path="/" component={Index} />
<Route path="/test" component={Test} />
</Route>
</Router>
), document.getElementById('content'))
That's because your using fetch
@see: the caveats section.
By default, fetch won't send any cookies to the server, resulting in unauthenticated requests if the site relies on maintaining a user session.