Search code examples
pythonauthenticationsecuritypyramid

Pyramid.security: Is getting user info from a database with unauthenticated_userid(request) really secure?


I'm trying to make an accesible cache of user data using Pyramid doc's "Making A “User Object” Available as a Request Attribute" example.

They're using this code to return a user object to set_request_property:

from pyramid.security import unauthenticated_userid

def get_user(request):
    # the below line is just an example, use your own method of
    # accessing a database connection here (this could even be another
    # request property such as request.db, implemented using this same
    # pattern).
    dbconn = request.registry.settings['dbconn']
    userid = unauthenticated_userid(request)
    if userid is not None:
        # this should return None if the user doesn't exist
        # in the database
        return dbconn['users'].query({'id':userid})

I don't understand why they're using unauthenticated_userid(request) to lookup user info from the database...isn't that insecure? That means that user might not be logged in, so why are you using that ID to get there private info from the database?

Shouldn't

    userid = authenticated_userid(request)

be used instead to make sure the user is logged in? What's the advantage of using unauthenticated_userid(request)? Please help me understand what's going on here.


Solution

  • The unauthenticated_userid call is a cheaper call; it looks up the user id from the request without going through the whole authentication process again.

    The key concept there is the word again. You should only use the method in views that have already been authorized. In other words, by the time you reach code that uses unauthenticated_userid you've already verified the user, and specifically do not want to do this again for this particular call.

    Authenticating users against a backend persistent storage can be expensive, especially if such a storage doesn't support caching. The unauthenticated_userid API method is an optimization where the request is basically your userid cache.