7

some strange behaviour I've found when trying to clear Starlette sessions state (using starlette.middleware.sessions.SessionMiddleware) while working through some OAuth/0Auth authentication examples.

In Flask, the following session clearing code on logout works perfectly fine:

@app.route('/logout')
def logout():
    session.clear()
    params = {'returnTo': url_for('home', _external=True), 'client_id': AUTH0_CLIENT_ID}
    return redirect(auth0.api_base_url + '/v2/logout?' + urlencode(params))

The equivalent request.session.clear() in Starlette fails to clear the session state and even after the logout code runs, I can still get to all the login-protected pages as the session state is somehow retained! I've annotated the code below - both the issue and the work-around.

async def logout(self, request):
    '''called when logout button is pressed - clear the session and redirect to root'''
    session = request.session      
    #session.clear()                # <- this doesn't achieve anything - session variables/cookies return on next request
    session.pop(PROFILE_KEY, None)  # <- popping just one of two works fine
    session.pop(JWT_PAYLOAD, None)  # <- popping the second (of two) leads to the same outcome as clear() (not good)
    session['logged_out'] = True    # <- but adding another dummy field/cookie fixes it
    #
    params = {'returnTo': 'https://my.awesome.page', 'client_id': AUTH0_CLIENT_ID}
    redir = self.auth0.api_base_url + '/v2/logout?' + urlencode(params,quote_via=quote_plus)
    #
    return RedirectResponse(url=redir)

So in a nutshell, Starlette doesn't seem to like it if you completely clear the session, and my work-around is to leave at least something in there, even just a dummy value that isn't used for anything.

Anyone had to deal with this before? Seems like an oddball issue. Am I missing something?

davidism
  • 121,510
  • 29
  • 395
  • 339
Dmytro Bugayev
  • 606
  • 9
  • 13

0 Answers0