简体   繁体   中英

Pyramid authentication: Why does it work?

I'm just now getting into authentication in my app, and all of the pyramid examples that I can find explain the straightforward parts very well, but handwave over the parts that don't make any sense to me.

Most of the examples look something like this:

login = request.params['login']
password = request.params['password']
if USERS.get(login) == password:
    headers = remember(request, login)
    return HTTPFound(location = came_from,
                     headers = headers)

And from init:

session_factory = UnencryptedCookieSessionFactoryConfig(
    settings['session.secret']
    )

authn_policy = SessionAuthenticationPolicy()
authz_policy = ACLAuthorizationPolicy()

Trying to track down the point in which the login actually happens, I'm assuming it's this one:

headers = remember(request, login)

It appears to me that what is going on is we're storing the username in the session cookie.

If I put this line in my app, the current user is magically logged in, but why?

  • How does pyramid know that I'm passing a username? It looks like I'm just passing the value of login. Further, this variable is named differently in different examples.
  • Even if it does know that it's a username, how does it connect it with the user ID? If I run authenticated_userid(request) afterwards, it works, but how has the system connected the username with the userid? I don't see any queries as part of the remember() documentation.

Pyramid's security system revolves around principals ; your login value is that principal. It is up to your code to provide remember() with a valid principal name; if your login name filled in the form is used as your principal, then that's great. If you are using an email address but use a database primary key as the principal string, then you'd have to map that yourself.

What exactly remember() does depends on your authentication policy ; it is up to the policy to 'know' from request to request what principal you asked it to remember.

If you are using the AuthTktAuthenticationPolicy policy , then the principal value is stored in a cryptographically signed cookie; your next response will have a Set-Cookie header added. Then next time a request comes in with that cookie, provided it is still valid and the signature checks out, the policy now 'knows' what principle is making that request.

When that request then tries to access a protected resource, Pyramid sees that a policy is in effect, and asks that policy for the current authenticated principle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM