'Starlette - storing auth status in session?

Is it okay / safe to keep the authentication result in Starlette session?

Example:

@app.get("/login")
async def login(request: Request):
    # ...assuming verifying user went ok
        request.session['logged_in_user'] = user.email  # THIS LINE
        return "Welcome"

def requires_auth(view):
    @wraps(view)
    def wrapper(request: Request, **kwargs: Optional[Dict]):
        if not request.session.get('logged_in_user'):
            raise HTTPException(status_code=403)
        return view(request, **kwargs)

    return wrapper

# Example of use
@app.get("/test")
@requires_auth
async def test():
    return JSONResponse({"hello": "world"})

I was trying to build a Facebook login feature for my app, but struggled a bit with the backend authentication solution which they provided in their example, and did the authentication a bit other way (seen above) - I wonder if it is safe though.



Solution 1:[1]

The general rule with session data is...

Never store something in it that would be considered confidential like a user id or username.

What you can do is instead generate a random string or uuid to represent a user so for example...

If my user id is '1234'. When I login, the server would generate a UUID for me then store that in the database with a reference to the user id of '1234'. Add the UUID to the session data and when they visit your page you can reverse the order. Look up the UUID, get the user id tied to it and now you know which user it is. But later on if something happens and you need to clear the UUID that's no big deal cause they can relogin and get a whole new UUID that will work the same way.

If someone gets a hold of my UUID they still dont know my username or email or my user id. So no information is gained from it. Though without proper security a stolen UUID can cause problems.

AS for authentication, if UUID exists and proper security is in place you can assume they are authenticated. If UUID doesn't exist in the database or no UUID is in the session then they are not authenticated.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TeddyBearSuicide