pyramid.authentication¶
Helper Classes¶
- class SessionAuthenticationHelper(prefix='auth.')[ソース]¶
A helper for use with a security policy which stores user data in the configured session.
Constructor Arguments
prefixA prefix used when storing the authentication parameters in the session. Defaults to 'auth.'. Optional.
- 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='sha512', parent_domain=False, domain=None, samesite='Lax')[ソース]¶
A helper class for security policies that obtains data from an "auth ticket" cookie.
Constructor Arguments
secretThe 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.
cookie_nameDefault:
auth_tkt. The cookie name used (string). Optional.secureDefault:
False. Only send the cookie back over a secure conn. Optional.include_ipDefault:
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_tktspecification 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.timeoutDefault:
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 isNone, the ticket never expires. Optional.reissue_timeDefault:
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 is0, 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
timeoutvalue to 1200 (20 mins) and set thereissue_timevalue to perhaps a tenth of thetimeoutvalue (120 or 2 mins). It's nonsensical to set thetimeoutvalue lower than thereissue_timevalue, as the ticket will never be reissued if so. However, such a configuration is not explicitly prevented.Optional.
max_ageDefault:
None. The max age of the auth_tkt cookie, in seconds. This differs fromtimeoutinasmuch astimeoutrepresents 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'sMax-AgeandExpiressettings 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 thantimeoutorreissue_time, although it is not explicitly prevented. Optional.pathDefault:
/. The path for which the auth_tkt cookie is valid. May be desirable if the application only serves part of a domain. Optional.http_onlyDefault:
False. Hide cookie from JavaScript by setting the HttpOnly flag. Not honored by all browsers. Optional.wild_domainDefault:
True. An auth_tkt cookie will be generated for the wildcard domain. If your site is hosted asexample.comthis will make the cookie available for sites underneathexample.comsuch aswww.example.com. Optional.parent_domainDefault:
False. An auth_tkt cookie will be generated for the parent domain of the current site. For example if your site is hosted underwww.example.coma cookie will be generated for.example.com. This can be useful if you have multiple sites sharing the same domain. This option supercedes thewild_domainoption. Optional.domainDefault:
None. If provided the auth_tkt cookie will only be set for this domain. This option is not compatible withwild_domainandparent_domain. Optional.hashalgDefault:
sha512(the literal string).Any hash algorithm supported by Python's
hashlib.new()function can be used as thehashalg.Cookies generated by different instances of AuthTktAuthenticationPolicy using different
hashalgoptions are not compatible. Switching thehashalgwill imply that all existing users with a valid cookie will be required to re-login.Optional.
debugDefault:
False. IfdebugisTrue, 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. Optional.samesiteDefault:
'Lax'. The 'samesite' option of the session cookie. Set the value toNoneto turn off the samesite option. Optional.バージョン 2.0 で変更: The default
hashalgwas changed frommd5tosha512.- 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 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.
- forget(request)[ソース]¶
Return a set of expires Set-Cookie headers, which will destroy any existing auth_tkt cookie when attached to a response
- identify(request)[ソース]¶
Return a dictionary with authentication information, or
Noneif no valid auth_tkt is attached torequest
- static parse_ticket(secret, ticket, ip, hashalg='md5')¶
Parse the ticket, returning (timestamp, userid, tokens, user_data).
If the ticket cannot be parsed, a
BadTicketexception will be raised with an explanation.
- remember(request, userid, max_age=None, tokens=())[ソース]¶
Return a set of Set-Cookie headers; when set into a response, these headers will represent a valid authentication ticket.
max_ageThe max age of the auth_tkt cookie, in seconds. When this value is set, the cookie's
Max-AgeandExpiressettings will be set, allowing the auth_tkt cookie to last between browser sessions. If this value isNone, themax_agevalue provided to the helper itself will be used as themax_agevalue. Default:None.tokensA sequence of strings that will be placed into the auth_tkt tokens field. Each string in the sequence must be of the Python
strtype 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:().
Helper Functions¶
- extract_http_basic_credentials(request)[ソース]¶
A helper function for extraction of HTTP Basic credentials from a given request.
Returns a
HTTPBasicCredentials2-tuple withusernameandpasswordattributes orNoneif no credentials could be found.
Authentication Policies¶
Authentication policies have been deprecated by the new security system. See Upgrading Authentication/Authorization for more information.
- 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='sha512', parent_domain=False, domain=None, samesite='Lax')[ソース]¶
A Pyramid authentication policy which obtains data from a Pyramid "auth ticket" cookie.
Constructor Arguments
secretThe 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.
callbackDefault:
None. A callback passed the userid and the request, expected to returnNoneif the userid doesn't exist or a sequence of principal identifiers (possibly empty) if the user does exist. IfcallbackisNone, the userid will be assumed to exist with no principals. Optional.
cookie_nameDefault:
auth_tkt. The cookie name used (string). Optional.
secureDefault:
False. Only send the cookie back over a secure conn. Optional.
include_ipDefault:
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_tktspecification 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.
timeoutDefault:
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 isNone, the ticket never expires. Optional.
reissue_timeDefault:
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 is0, 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
timeoutvalue to 1200 (20 mins) and set thereissue_timevalue to perhaps a tenth of thetimeoutvalue (120 or 2 mins). It's nonsensical to set thetimeoutvalue lower than thereissue_timevalue, as the ticket will never be reissued if so. However, such a configuration is not explicitly prevented.Optional.
max_ageDefault:
None. The max age of the auth_tkt cookie, in seconds. This differs fromtimeoutinasmuch astimeoutrepresents 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'sMax-AgeandExpiressettings 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 thantimeoutorreissue_time, although it is not explicitly prevented. Optional.
pathDefault:
/. The path for which the auth_tkt cookie is valid. May be desirable if the application only serves part of a domain. Optional.
http_onlyDefault:
False. Hide cookie from JavaScript by setting the HttpOnly flag. Not honored by all browsers. Optional.
wild_domainDefault:
True. An auth_tkt cookie will be generated for the wildcard domain. If your site is hosted asexample.comthis will make the cookie available for sites underneathexample.comsuch aswww.example.com. Optional.
parent_domainDefault:
False. An auth_tkt cookie will be generated for the parent domain of the current site. For example if your site is hosted underwww.example.coma cookie will be generated for.example.com. This can be useful if you have multiple sites sharing the same domain. This option supercedes thewild_domainoption. Optional.
domainDefault:
None. If provided the auth_tkt cookie will only be set for this domain. This option is not compatible withwild_domainandparent_domain. Optional.
hashalgDefault:
sha512(the literal string).Any hash algorithm supported by Python's
hashlib.new()function can be used as thehashalg.Cookies generated by different instances of AuthTktAuthenticationPolicy using different
hashalgoptions are not compatible. Switching thehashalgwill imply that all existing users with a valid cookie will be required to re-login.Optional.
debugDefault:
False. IfdebugisTrue, 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.
samesiteDefault:
'Lax'. The 'samesite' option of the session cookie. Set the value to the string'None'to turn off the samesite option.バージョン 1.4 で変更: Added the
hashalgoption, defaulting tosha512.バージョン 1.5 で変更: Added the
domainoption.Added the
parent_domainoption.バージョン 1.10 で変更: Added the
samesiteoption and made the default'Lax'.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
callbackis registered, this will return the userid if and only if the callback returns a value that is notNone.
- effective_principals(request)¶
A list of effective principals derived from request.
This will return a list of principals including, at least,
pyramid.authorization.Everyone. If there is no authenticated userid, or thecallbackreturnsNone, this will be the only principal:return [Everyone]If the
callbackdoes not returnNoneand an authenticated userid is found, then the principals will includepyramid.authorization.Authenticated, theauthenticated_useridand the list of principals returned by thecallback:extra_principals = callback(userid, request) return [Everyone, Authenticated, userid] + extra_principals
- class RemoteUserAuthenticationPolicy(environ_key='REMOTE_USER', callback=None, debug=False)[ソース]¶
A Pyramid authentication policy which obtains data from the
REMOTE_USERWSGI environment variable.Constructor Arguments
environ_keyDefault:
REMOTE_USER. The key in the WSGI environ which provides the userid.
callbackDefault:
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. Ifcallbackis None, the userid will be assumed to exist with no group principals.
debugDefault:
False. IfdebugisTrue, 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
callbackis registered, this will return the userid if and only if the callback returns a value that is notNone.
- effective_principals(request)¶
A list of effective principals derived from request.
This will return a list of principals including, at least,
pyramid.authorization.Everyone. If there is no authenticated userid, or thecallbackreturnsNone, this will be the only principal:return [Everyone]If the
callbackdoes not returnNoneand an authenticated userid is found, then the principals will includepyramid.authorization.Authenticated, theauthenticated_useridand the list of principals returned by thecallback:extra_principals = callback(userid, request) return [Everyone, Authenticated, userid] + extra_principals
- forget(request)[ソース]¶
A no-op. The
REMOTE_USERdoes not provide a protocol for forgetting the user. This will be application-specific and can be done somewhere else or in a subclass.
- class SessionAuthenticationPolicy(prefix='auth.', callback=None, debug=False)[ソース]¶
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
prefixA prefix used when storing the authentication parameters in the session. Defaults to 'auth.'. Optional.
callbackDefault:
None. A callback passed the userid and the request, expected to returnNoneif the userid doesn't exist or a sequence of principal identifiers (possibly empty) if the user does exist. IfcallbackisNone, the userid will be assumed to exist with no principals. Optional.
debugDefault:
False. IfdebugisTrue, 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
callbackis registered, this will return the userid if and only if the callback returns a value that is notNone.
- effective_principals(request)¶
A list of effective principals derived from request.
This will return a list of principals including, at least,
pyramid.authorization.Everyone. If there is no authenticated userid, or thecallbackreturnsNone, this will be the only principal:return [Everyone]If the
callbackdoes not returnNoneand an authenticated userid is found, then the principals will includepyramid.authorization.Authenticated, theauthenticated_useridand the list of principals returned by thecallback:extra_principals = callback(userid, request) return [Everyone, Authenticated, userid] + extra_principals
- class BasicAuthAuthenticationPolicy(check, realm='Realm', debug=False)[ソース]¶
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
checkA callback function passed a username, password and request, in that order as positional arguments. Expected to return
Noneif the userid doesn't exist or a sequence of principal identifiers (possibly empty) if the user does exist.
realmDefault:
"Realm". The Basic Auth Realm string. Usually displayed to the user by the browser in the login dialog.
debugDefault:
False. IfdebugisTrue, 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 forbidden_view(request): if request.authenticated_userid is None: response = HTTPUnauthorized() response.headers.update(forget(request)) return response return HTTPForbidden()
- authenticated_userid(request)¶
Return the authenticated userid or
None.If no callback is registered, this will be the same as
unauthenticated_userid.If a
callbackis registered, this will return the userid if and only if the callback returns a value that is notNone.
- effective_principals(request)¶
A list of effective principals derived from request.
This will return a list of principals including, at least,
pyramid.authorization.Everyone. If there is no authenticated userid, or thecallbackreturnsNone, this will be the only principal:return [Everyone]If the
callbackdoes not returnNoneand an authenticated userid is found, then the principals will includepyramid.authorization.Authenticated, theauthenticated_useridand the list of principals returned by thecallback:extra_principals = callback(userid, request) return [Everyone, Authenticated, userid] + extra_principals
- forget(request)[ソース]¶
Returns challenge headers. This should be attached to a response to indicate that credentials are required.
- class RepozeWho1AuthenticationPolicy(identifier_name='auth_tkt', callback=None)[ソース]¶
A Pyramid authentication policy which obtains data from the
repoze.who1.X WSGI 'API' (therepoze.who.identitykey in the WSGI environment).Constructor Arguments
identifier_nameDefault:
auth_tkt. Therepoze.whoplugin name that performs remember/forget. Optional.
callbackDefault:
None. A callback passed therepoze.whoidentity and the request, expected to returnNoneif the user represented by the identity doesn't exist or a sequence of principal identifiers (possibly empty) representing groups if the user does exist. Ifcallbackis 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)[ソース]¶
Return the authenticated userid or
None.If no callback is registered, this will be the same as
unauthenticated_userid.If a
callbackis registered, this will return the userid if and only if the callback returns a value that is notNone.
- effective_principals(request)[ソース]¶
A list of effective principals derived from the identity.
This will return a list of principals including, at least,
pyramid.authorization.Everyone. If there is no identity, or thecallbackreturnsNone, this will be the only principal.If the
callbackdoes not returnNoneand an identity is found, then the principals will includepyramid.authorization.Authenticated, theauthenticated_useridand the list of principals returned by thecallback.
- forget(request)[ソース]¶
Forget the current authenticated user.
Return headers that, if included in a response, will delete the cookie responsible for tracking the current user.