Documentation in progress Edit me on GitHub

pyramid.authentication

Authentication Policies

class AuthTktAuthenticationPolicy(secret, callback=None, cookie_name='auth_tkt', secure=False, include_ip=False, timeout=None, reissue_time=None, max_age=None, path='/', http_only=False, wild_domain=True, debug=False, hashalg=<object object at 0x7fcc0e620bd0>, parent_domain=False, domain=None)[source]

A Pyramid authentication policy which obtains data from a Pyramid "auth ticket" cookie.

Warning

The default hash algorithm used in this policy is MD5 and has known hash collision vulnerabilities. The risk of an exploit is low. However, for improved authentication security, use hashalg='sha512'.

Constructor Arguments

secret

The secret (a string) used for auth_tkt cookie signing. This value should be unique across all values provided to Pyramid for various subsystem secrets (see Admonishment Against Secret-Sharing). Required.

callback

Default: None. A callback passed the userid and the request, expected to return None if the userid doesn't exist or a sequence of principal identifiers (possibly empty) if the user does exist. If callback is None, the userid will be assumed to exist with no principals. Optional.

cookie_name

Default: auth_tkt. The cookie name used (string). Optional.

secure

Default: False. Only send the cookie back over a secure conn. Optional.

include_ip

Default: False. Make the requesting IP address part of the authentication data in the cookie. Optional.

For IPv6 this option is not recommended. The mod_auth_tkt specification does not specify how to handle IPv6 addresses, so using this option in combination with IPv6 addresses may cause an incompatible cookie. It ties the authentication ticket to that individual's IPv6 address.

timeout

Default: None. Maximum number of seconds which a newly issued ticket will be considered valid. After this amount of time, the ticket will expire (effectively logging the user out). If this value is None, the ticket never expires. Optional.

reissue_time

Default: None. If this parameter is set, it represents the number of seconds that must pass before an authentication token cookie is automatically reissued as the result of a request which requires authentication. The duration is measured as the number of seconds since the last auth_tkt cookie was issued and 'now'. If this value is 0, a new ticket cookie will be reissued on every request which requires authentication.

A good rule of thumb: if you want auto-expired cookies based on inactivity: set the timeout value to 1200 (20 mins) and set the reissue_time value to perhaps a tenth of the timeout value (120 or 2 mins). It's nonsensical to set the timeout value lower than the reissue_time value, as the ticket will never be reissued if so. However, such a configuration is not explicitly prevented.

Optional.

max_age

Default: None. The max age of the auth_tkt cookie, in seconds. This differs from timeout inasmuch as timeout represents the lifetime of the ticket contained in the cookie, while this value represents the lifetime of the cookie itself. When this value is set, the cookie's Max-Age and Expires settings will be set, allowing the auth_tkt cookie to last between browser sessions. It is typically nonsensical to set this to a value that is lower than timeout or reissue_time, although it is not explicitly prevented. Optional.

path

Default: /. The path for which the auth_tkt cookie is valid. May be desirable if the application only serves part of a domain. Optional.

http_only

Default: False. Hide cookie from JavaScript by setting the HttpOnly flag. Not honored by all browsers. Optional.

wild_domain

Default: True. An auth_tkt cookie will be generated for the wildcard domain. If your site is hosted as example.com this will make the cookie available for sites underneath example.com such as www.example.com. Optional.

parent_domain

Default: False. An auth_tkt cookie will be generated for the parent domain of the current site. For example if your site is hosted under www.example.com a cookie will be generated for .example.com. This can be useful if you have multiple sites sharing the same domain. This option supercedes the wild_domain option. Optional.

This option is available as of Pyramid 1.5.

domain

Default: None. If provided the auth_tkt cookie will only be set for this domain. This option is not compatible with wild_domain and parent_domain. Optional.

This option is available as of Pyramid 1.5.

hashalg

Default: md5 (the literal string).

Any hash algorithm supported by Python's hashlib.new() function can be used as the hashalg.

Cookies generated by different instances of AuthTktAuthenticationPolicy using different hashalg options are not compatible. Switching the hashalg will imply that all existing users with a valid cookie will be required to re-login.

A warning is emitted at startup if an explicit hashalg is not passed. This is for backwards compatibility reasons.

This option is available as of Pyramid 1.4.

Optional.

Note

md5 is the default for backwards compatibility reasons. However, if you don't specify md5 as the hashalg explicitly, a warning is issued at application startup time. An explicit value of sha512 is recommended for improved security, and sha512 will become the default in a future Pyramid version.

debug

Default: False. If debug is True, log messages to the Pyramid debug logger about the results of various authentication steps. The output from debugging is useful for reporting to maillist or IRC channels when asking for support.

Objects of this class implement the interface described by pyramid.interfaces.IAuthenticationPolicy.

authenticated_userid(request)

Return the authenticated userid or None.

If no callback is registered, this will be the same as unauthenticated_userid.

If a callback is registered, this will return the userid if and only if the callback returns a value that is not None.

effective_principals(request)

A list of effective principals derived from request.

This will return a list of principals including, at least, pyramid.security.Everyone. If there is no authenticated userid, or the callback returns None, this will be the only principal:

return [Everyone]

If the callback does not return None and an authenticated userid is found, then the principals will include pyramid.security.Authenticated, the authenticated_userid and the list of principals returned by the callback:

extra_principals = callback(userid, request)
return [Everyone, Authenticated, userid] + extra_principals
forget(request)[source]

A list of headers which will delete appropriate cookies.

remember(request, principal, **kw)[source]

Accepts the following kw args: max_age=<int-seconds>, ``tokens=<sequence-of-ascii-strings>.

Return a list of headers which will set appropriate cookies on the response.

unauthenticated_userid(request)[source]

The userid key within the auth_tkt cookie.

class RemoteUserAuthenticationPolicy(environ_key='REMOTE_USER', callback=None, debug=False)[source]

A Pyramid authentication policy which obtains data from the REMOTE_USER WSGI environment variable.

Constructor Arguments

environ_key

Default: REMOTE_USER. The key in the WSGI environ which provides the userid.

callback

Default: None. A callback passed the userid and the request, expected to return None if the userid doesn't exist or a sequence of principal identifiers (possibly empty) representing groups if the user does exist. If callback is None, the userid will be assumed to exist with no group principals.

debug

Default: False. If debug is True, log messages to the Pyramid debug logger about the results of various authentication steps. The output from debugging is useful for reporting to maillist or IRC channels when asking for support.

Objects of this class implement the interface described by pyramid.interfaces.IAuthenticationPolicy.

authenticated_userid(request)

Return the authenticated userid or None.

If no callback is registered, this will be the same as unauthenticated_userid.

If a callback is registered, this will return the userid if and only if the callback returns a value that is not None.

effective_principals(request)

A list of effective principals derived from request.

This will return a list of principals including, at least, pyramid.security.Everyone. If there is no authenticated userid, or the callback returns None, this will be the only principal:

return [Everyone]

If the callback does not return None and an authenticated userid is found, then the principals will include pyramid.security.Authenticated, the authenticated_userid and the list of principals returned by the callback:

extra_principals = callback(userid, request)
return [Everyone, Authenticated, userid] + extra_principals
forget(request)[source]

A no-op. The REMOTE_USER does not provide a protocol for forgetting the user. This will be application-specific and can be done somewhere else or in a subclass.

remember(request, principal, **kw)[source]

A no-op. The REMOTE_USER does not provide a protocol for remembering the user. This will be application-specific and can be done somewhere else or in a subclass.

unauthenticated_userid(request)[source]

The REMOTE_USER value found within the environ.

class SessionAuthenticationPolicy(prefix='auth.', callback=None, debug=False)[source]

A Pyramid authentication policy which gets its data from the configured session. For this authentication policy to work, you will have to follow the instructions in the Sessions to configure a session factory.

Constructor Arguments

prefix

A prefix used when storing the authentication parameters in the session. Defaults to 'auth.'. Optional.

callback

Default: None. A callback passed the userid and the request, expected to return None if the userid doesn't exist or a sequence of principal identifiers (possibly empty) if the user does exist. If callback is None, the userid will be assumed to exist with no principals. Optional.

debug

Default: False. If debug is True, log messages to the Pyramid debug logger about the results of various authentication steps. The output from debugging is useful for reporting to maillist or IRC channels when asking for support.
authenticated_userid(request)

Return the authenticated userid or None.

If no callback is registered, this will be the same as unauthenticated_userid.

If a callback is registered, this will return the userid if and only if the callback returns a value that is not None.

effective_principals(request)

A list of effective principals derived from request.

This will return a list of principals including, at least, pyramid.security.Everyone. If there is no authenticated userid, or the callback returns None, this will be the only principal:

return [Everyone]

If the callback does not return None and an authenticated userid is found, then the principals will include pyramid.security.Authenticated, the authenticated_userid and the list of principals returned by the callback:

extra_principals = callback(userid, request)
return [Everyone, Authenticated, userid] + extra_principals
forget(request)[source]

Remove the stored principal from the session.

remember(request, principal, **kw)[source]

Store a principal in the session.

class BasicAuthAuthenticationPolicy(check, realm='Realm', debug=False)[source]

A Pyramid authentication policy which uses HTTP standard basic authentication protocol to authenticate users. To use this policy you will need to provide a callback which checks the supplied user credentials against your source of login data.

Constructor Arguments

check

A callback function passed a username, password and request, in that order as positional arguments. Expected to return None if the userid doesn't exist or a sequence of principal identifiers (possibly empty) if the user does exist.

realm

Default: "Realm". The Basic Auth Realm string. Usually displayed to the user by the browser in the login dialog.

debug

Default: False. If debug is True, log messages to the Pyramid debug logger about the results of various authentication steps. The output from debugging is useful for reporting to maillist or IRC channels when asking for support.

Issuing a challenge

Regular browsers will not send username/password credentials unless they first receive a challenge from the server. The following recipe will register a view that will send a Basic Auth challenge to the user whenever there is an attempt to call a view which results in a Forbidden response:

from pyramid.httpexceptions import HTTPUnauthorized
from pyramid.security import forget
from pyramid.view import forbidden_view_config

@forbidden_view_config()
def basic_challenge(request):
    response = HTTPUnauthorized()
    response.headers.update(forget(request))
    return response
authenticated_userid(request)

Return the authenticated userid or None.

If no callback is registered, this will be the same as unauthenticated_userid.

If a callback is registered, this will return the userid if and only if the callback returns a value that is not None.

effective_principals(request)

A list of effective principals derived from request.

This will return a list of principals including, at least, pyramid.security.Everyone. If there is no authenticated userid, or the callback returns None, this will be the only principal:

return [Everyone]

If the callback does not return None and an authenticated userid is found, then the principals will include pyramid.security.Authenticated, the authenticated_userid and the list of principals returned by the callback:

extra_principals = callback(userid, request)
return [Everyone, Authenticated, userid] + extra_principals
forget(request)[source]

Returns challenge headers. This should be attached to a response to indicate that credentials are required.

remember(request, principal, **kw)[source]

A no-op. Basic authentication does not provide a protocol for remembering the user. Credentials are sent on every request.

unauthenticated_userid(request)[source]

The userid parsed from the Authorization request header.

class RepozeWho1AuthenticationPolicy(identifier_name='auth_tkt', callback=None)[source]

A Pyramid authentication policy which obtains data from the repoze.who 1.X WSGI 'API' (the repoze.who.identity key in the WSGI environment).

Constructor Arguments

identifier_name

Default: auth_tkt. The repoze.who plugin name that performs remember/forget. Optional.

callback

Default: None. A callback passed the repoze.who identity and the request, expected to return None if the user represented by the identity doesn't exist or a sequence of principal identifiers (possibly empty) representing groups if the user does exist. If callback is None, the userid will be assumed to exist with no group principals.

Objects of this class implement the interface described by pyramid.interfaces.IAuthenticationPolicy.

authenticated_userid(request)[source]

Return the authenticated userid or None.

If no callback is registered, this will be the same as unauthenticated_userid.

If a callback is registered, this will return the userid if and only if the callback returns a value that is not None.

effective_principals(request)[source]

A list of effective principals derived from the identity.

This will return a list of principals including, at least, pyramid.security.Everyone. If there is no identity, or the callback returns None, this will be the only principal.

If the callback does not return None and an identity is found, then the principals will include pyramid.security.Authenticated, the authenticated_userid and the list of principals returned by the callback.

forget(request)[source]

Forget the current authenticated user.

Return headers that, if included in a response, will delete the cookie responsible for tracking the current user.

remember(request, principal, **kw)[source]

Store the principal as repoze.who.userid.

The identity to authenticated to repoze.who will contain the given principal as userid, and provide all keyword arguments as additional identity keys. Useful keys could be max_age or userdata.

unauthenticated_userid(request)[source]

Return the repoze.who.userid key from the detected identity.

Helper Classes

class AuthTktCookieHelper(secret, cookie_name='auth_tkt', secure=False, include_ip=False, timeout=None, reissue_time=None, max_age=None, http_only=False, path='/', wild_domain=True, hashalg='md5', parent_domain=False, domain=None)[source]

A helper class for use in third-party authentication policy implementations. See pyramid.authentication.AuthTktAuthenticationPolicy for the meanings of the constructor arguments.

class AuthTicket(secret, userid, ip, tokens=(), user_data='', time=None, cookie_name='auth_tkt', secure=False, hashalg='md5')

This class represents an authentication token. You must pass in the shared secret, the userid, and the IP address. Optionally you can include tokens (a list of strings, representing role names), 'user_data', which is arbitrary data available for your own use in later scripts. Lastly, you can override the cookie name and timestamp.

Once you provide all the arguments, use .cookie_value() to generate the appropriate authentication ticket.

Usage:

token = AuthTicket('sharedsecret', 'username',
    os.environ['REMOTE_ADDR'], tokens=['admin'])
val = token.cookie_value()
exception AuthTktCookieHelper.BadTicket(msg, expected=None)

Exception raised when a ticket can't be parsed. If we get far enough to determine what the expected digest should have been, expected is set. This should not be shown by default, but can be useful for debugging.

AuthTktCookieHelper.forget(request)[source]

Return a set of expires Set-Cookie headers, which will destroy any existing auth_tkt cookie when attached to a response

AuthTktCookieHelper.identify(request)[source]

Return a dictionary with authentication information, or None if no valid auth_tkt is attached to request

static AuthTktCookieHelper.parse_ticket(secret, ticket, ip, hashalg='md5')

Parse the ticket, returning (timestamp, userid, tokens, user_data).

If the ticket cannot be parsed, a BadTicket exception will be raised with an explanation.

AuthTktCookieHelper.remember(request, userid, max_age=None, tokens=())[source]

Return a set of Set-Cookie headers; when set into a response, these headers will represent a valid authentication ticket.

max_age
The max age of the auth_tkt cookie, in seconds. When this value is set, the cookie's Max-Age and Expires settings will be set, allowing the auth_tkt cookie to last between browser sessions. If this value is None, the max_age value provided to the helper itself will be used as the max_age value. Default: None.
tokens
A sequence of strings that will be placed into the auth_tkt tokens field. Each string in the sequence must be of the Python str type and must match the regex ^[A-Za-z][A-Za-z0-9+_-]*$. Tokens are available in the returned identity when an auth_tkt is found in the request and unpacked. Default: ().

Table Of Contents

Previous topic

Running a Pyramid Application under mod_wsgi

Next topic

pyramid.authorization