This package provides a flexible and pluggable authentication utility for Zope
3, using `zope.pluggableauth`. Several common plugins are provided.
.. contents::
================================
Pluggable-Authentication Utility
================================
The Pluggable-Authentication Utility (PAU) provides a framework for
authenticating principals and associating information with them. It uses
plugins and subscribers to get its work done.
For a pluggable-authentication utility to be used, it should be
registered as a utility providing the
`zope.authentication.interfaces.IAuthentication` interface.
Authentication
--------------
The primary job of PAU is to authenticate principals. It uses two types of
plug-ins in its work:
- Credentials Plugins
- Authenticator Plugins
Credentials plugins are responsible for extracting user credentials from a
request. A credentials plugin may in some cases issue a 'challenge' to obtain
credentials. For example, a 'session' credentials plugin reads credentials
from a session (the "extraction"). If it cannot find credentials, it will
redirect the user to a login form in order to provide them (the "challenge").
Authenticator plugins are responsible for authenticating the credentials
extracted by a credentials plugin. They are also typically able to create
principal objects for credentials they successfully authenticate.
Given a request object, the PAU returns a principal object, if it can. The PAU
does this by first iterateing through its credentials plugins to obtain a
set of credentials. If it gets credentials, it iterates through its
authenticator plugins to authenticate them.
If an authenticator succeeds in authenticating a set of credentials, the PAU
uses the authenticator to create a principal corresponding to the credentials.
The authenticator notifies subscribers if an authenticated principal is
created. Subscribers are responsible for adding data, especially groups, to
the principal. Typically, if a subscriber adds data, it should also add
corresponding interface declarations.
Simple Credentials Plugin
~~~~~~~~~~~~~~~~~~~~~~~~~
To illustrate, we'll create a simple credentials plugin::
>>> from zope import interface
>>> from zope.app.authentication import interfaces
>>> @interface.implementer(interfaces.ICredentialsPlugin)
... class MyCredentialsPlugin(object):
...
...
... def extractCredentials(self, request):
... return request.get('credentials')
...
... def challenge(self, request):
... pass # challenge is a no-op for this plugin
...
... def logout(self, request):
... pass # logout is a no-op for this plugin
As a plugin, MyCredentialsPlugin needs to be registered as a named utility::
>>> myCredentialsPlugin = MyCredentialsPlugin()
>>> provideUtility(myCredentialsPlugin, name='My Credentials Plugin')
Simple Authenticator Plugin
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Next we'll create a simple authenticator plugin. For our plugin, we'll need
an implementation of IPrincipalInfo::
>>> @interface.implementer(interfaces.IPrincipalInfo)
... class PrincipalInfo(object):
...
... def __init__(self, id, title, description):
... self.id = id
... self.title = title
... self.description = description
...
... def __repr__(self):
... return 'PrincipalInfo(%r)' % self.id
Our authenticator uses this type when it creates a principal info::
>>> @interface.implementer(interfaces.IAuthenticatorPlugin)
... class MyAuthenticatorPlugin(object):
...
... def authenticateCredentials(self, credentials):
... if credentials == 'secretcode':
... return PrincipalInfo('bob', 'Bob', '')
...
... def principalInfo(self, id):
... pass # plugin not currently supporting search
As with the credentials plugin, the authenticator plugin must be registered
as a named utility::
>>> myAuthenticatorPlugin = MyAuthenticatorPlugin()
>>> provideUtility(myAuthenticatorPlugin, name='My Authenticator Plugin')
Principal Factories
~~~~~~~~~~~~~~~~~~~
While authenticator plugins provide principal info, they are not responsible
for creating principals. This function is performed by factory adapters. For
these tests we'll borrow some factories from the principal folder::
>>> from zope.app.authentication import principalfolder
>>> provideAdapter(principalfolder.AuthenticatedPrincipalFactory)
>>> provideAdapter(principalfolder.FoundPrincipalFactory)
For more information on these factories, see their docstrings.
Configuring a PAU
~~~~~~~~~~~~~~~~~
Finally, we'll create the PAU itself::
>>> from zope.app import authentication
>>> pau = authentication.PluggableAuthentication('xyz_')
and configure it with the two plugins::
>>> pau.credentialsPlugins = ('My Credentials Plugin', )
>>> pau.authenticatorPlugins = ('My Authenticator Plugin', )
Using the PAU to Authenticate
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We can now use the PAU to authenticate a sample request::
>>> from zope.publisher.browser import TestRequest
>>> print(pau.authenticate(TestRequest()))
None
In this case, we cannot authenticate an empty request. In the same way, we
will not be able to authenticate a request with the wrong credentials::
>>> print(pau.authenticate(TestRequest(credentials='let me in!')))
None
However, if we provide the proper credentials::
>>> request = TestRequest(credentials='secretcode')
>>> principal = pau.authenticate(request)
>>> principal
Principal('xyz_bob')
we get an authenticated principal.
Authenticated Principal Creates Events
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We can verify that the appropriate event was published::
>>> [event] = getEvents(interfaces.IAuthenticatedPrincipalCreated)
>>> event.principal is principal
True
>>> event.info
PrincipalInfo('bob')
>>> event.request is request
True
The info object has the id, title, and description of the principal. The info
object is also generated by the authenticator plugin, so the plugin may
itself have provided additional information on the info object::
>>> event.info.title
'Bob'
>>> event.info.id # does not include pau prefix
'bob'
>>> event.info.description
''
It is also decorated with two other attributes, credentialsPlugin and
authenticatorPlugin: these are the plugins used to extract credentials for and
authenticate this principal. These attributes can be useful for subscribers
that want to react to the plugins used. For instance, subscribers can
determine that a given credential plugin does or does not support logout, and
provide information usable to show or hide logout user interface::
>>> event.info.credentialsPlugin is myCredentialsPlugin
True
>>> event.info.authenticatorPlugin is myAuthenticatorPlugin
True
Normally, we provide subscribers to these events that add additional
information to the principal. For example, we'll add one that sets
the title::
>>> def add_info(event):
... event.principal.title = event.info.title
>>> provideHandler(add_info, [interfaces.IAuthenticatedPrincipalCreated])
Now, if we authenticate a principal, its title is set::
>>> principal = pau.authenticate(request)
>>> principal.title
'Bob'
Multiple Authenticator Plugins
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The PAU works with multiple authenticator plugins. It uses each plugin, in the
order specified in the PAU's authenticatorPlugins attribute, to authenticate
a set of credentials.
To illustrate, we'll create another authenticator::
>>> class MyAuthenticatorPlugin2(MyAuthenticatorPlugin):
...
... def authenticateCredentials(self, credentials):
... if credentials == 'secretcode':
... return PrincipalInfo('black', 'Black Spy', '')
... elif credentials == 'hiddenkey':
... return PrincipalInfo('white', 'White Spy', '')
>>> provideUtility(MyAuthenticatorPlugin2(), name='My Authenticator Plugin 2')
If we put it before the original authenticator::
>>> pau.authenticatorPlugins = (
... 'My Authenticator Plugin 2',
... 'My Authenticator Plugin')
Then it will be given the first opportunity to authenticate a request::
>>> pau.authenticate(TestRequest(credentials='secretcode'))
Principal('xyz_black')
If neither plugins can authenticate, pau returns None::
>>> print(pau.authenticate(TestRequest(credentials='let me in!!')))
None
When we change the order of the authenticator plugins::
>>> pau.authenticatorPlugins = (
... 'My Authenticator Plugin',
... 'My Authenticator Plugin 2')
we see that our original plugin is now acting first::
>>> pau.authenticate(TestRequest(credentials='secretcode'))
Principal('xyz_bob')
The second plugin, however, gets a chance to authenticate if first does not::
>>> pau.authenticate(TestRequest(credentials='hiddenkey'))
Principal('xyz_white')
Multiple Credentials Plugins
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As with with authenticators, we can specify multiple credentials plugins. To
illustrate, we'll create a credentials plugin that extracts credentials from
a request form::
>>> @interface.implementer(interfaces.ICredentialsPlugin)
... class FormCredentialsPlugin:
...
... def extractCredentials(self, request):
... return request.form.get('my_credentials')
...
... def challenge(self, request):
... pass
...
... def logout(request):
... pass
>>> provideUtility(FormCredentialsPlugin(),
... name='Form Credentials Plugin')
and insert the new credentials plugin before the existing plugin::
>>> pau.credentialsPlugins = (
... 'Form Credentials Plugin',
... 'My Credentials Plugin')
The PAU will use each plugin in order to try and obtain credentials from a
request::
>>> pau.authenticate(TestRequest(credentials='secretcode',
... form={'my_credentials': 'hiddenkey'}))
Principal('xyz_white')
In this case, the first credentials plugin succeeded in getting credentials
from the form and the second authenticator was able to authenticate the
credentials. Specifically, the PAU went through these steps:
- Get credentials using 'Form Credentials Plugin'
- Got 'hiddenkey' credentials using 'Form Credentials Plugin', try to
authenticate using 'My Authenticator Plugin'
- Failed to authenticate 'hiddenkey' with 'My Authenticator Plugin', try
'My Authenticator Plugin 2'
- Succeeded in authenticating with 'My Authenticator Plugin 2'
Let's try a different scenario::
>>> pau.authenticate(TestRequest(credentials='secretcode'))
Principal('xyz_bob')
In this case, the PAU went through these steps::
- Get credentials using 'Form Credentials Plugin'
- Failed to get credentials using 'Form Credentials Plugin', try
'My Credentials Plugin'
- Got 'scecretcode' credentials using 'My Credentials Plugin', try to
authenticate using 'My Authenticator Plugin'
- Succeeded in authenticating with 'My Authenticator Plugin'
Let's try a slightly more complex scenario::
>>> pau.authenticate(TestRequest(credentials='hiddenkey',
... form={'my_credentials': 'bogusvalue'}))
Principal('xyz_white')
This highlights PAU's ability to use multiple plugins for authentication:
- Get credentials using 'Form Credentials Plugin'
- Got 'bogusvalue' credentials using 'Form Credentials Plugin', try to
authenticate using 'My Authenticator Plugin'
- Failed to authenticate 'boguskey' with 'My Authenticator Plugin', try
'My Authenticator Plugin 2'
- Failed to authenticate 'boguskey' with 'My Authenticator Plugin 2' --
there are no more authenticators to try, so lets try the next credentials
plugin for some new credentials
- Get credentials using 'My Credentials Plugin'
- Got 'hiddenkey' credentials using 'My Credentials Plugin', try to
authenticate using 'My Authenticator Plugin'
- Failed to authenticate 'hiddenkey' using 'My Authenticator Plugin', try
'My Authenticator Plugin 2'
- Succeeded in authenticating with 'My Authenticator Plugin 2' (shouts and
cheers!)
Principal Searching
-------------------
As a component that provides IAuthentication, a PAU lets you lookup a
principal with a principal ID. The PAU looks up a principal by delegating to
its authenticators. In our example, none of the authenticators implement this
search capability, so when we look for a principal::
>>> print(pau.getPrincipal('xyz_bob'))
Traceback (most recent call last):
zope.authentication.interfaces.PrincipalLookupError: bob
>>> print(pau.getPrincipal('white'))
Traceback (most recent call last):
zope.authentication.interfaces.PrincipalLookupError: white
>>> print(pau.getPrincipal('black'))
Traceback (most recent call last):
zope.authentication.interfaces.PrincipalLookupError: black
For a PAU to support search, it needs to be configured with one or more
authenticator plugins that support search. To illustrate, we'll create a new
authenticator::
>>> @interface.implementer(interfaces.IAuthenticatorPlugin)
... class SearchableAuthenticatorPlugin:
...
... def __init__(self):
... self.infos = {}
... self.ids = {}
...
... def principalInfo(self, id):
... return self.infos.get(id)
...
... def authenticateCredentials(self, credentials):
... id = self.ids.get(credentials)
... if id is not None:
... return self.infos[id]
...
... def add(self, id, title, description, credentials):
... self.infos[id] = PrincipalInfo(id, title, description)
... self.ids[credentials] = id
This class is typical of an authenticator plugin. It can both authenticate
principals and find principals given a ID. While there are cases
where an authenticator may opt to not perform one of these two functions, they
are less typical.
As with any plugin, we need to register it as a utility::
>>> searchable = SearchableAuthenticatorPlugin()
>>> provideUtility(searchable, name='Searchable Authentication Plugin')
We'll now configure the PAU to use only the searchable authenticator::
>>> pau.authenticatorPlugins = ('Searchable Authentication Plugin',)
and add some principals to the authenticator::
>>> searchable.add('bob', 'Bob', 'A nice guy', 'b0b')
>>> searchable.add('white', 'White Spy', 'Sneaky', 'deathtoblack')
Now when we ask the PAU to find a principal::
>>> pau.getPrincipal('xyz_bob')
Principal('xyz_bob')
but only those it knows about::
>>> print(pau.getPrincipal('black'))
Traceback (most recent call last):
zope.authentication.interfaces.PrincipalLookupError: black
Found Principal Creates Events
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As evident in the authenticator's 'createFoundPrincipal' method (see above),
a FoundPrincipalCreatedEvent is published when the authenticator finds a
principal on behalf of PAU's 'getPrincipal'::
>>> clearEvents()
>>> principal = pau.getPrincipal('xyz_white')
>>> principal
Principal('xyz_white')
>>> [event] = getEvents(interfaces.IFoundPrincipalCreated)
>>> event.principal is principal
True
>>> event.info
PrincipalInfo('white')
The info has an authenticatorPlugin, but no credentialsPlugin, since none was
used::
>>> event.info.credentialsPlugin is None
True
>>> event.info.authenticatorPlugin is searchable
True
As we have seen with authenticated principals, it is common to subscribe to
principal created events to add information to the newly created principal.
In this case, we need to subscribe to IFoundPrincipalCreated events::
>>> provideHandler(add_info, [interfaces.IFoundPrincipalCreated])
Now when a principal is created as a result of a search, it's title and
description will be set (by the add_info handler function).
Multiple Authenticator Plugins
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As with the other operations we've seen, the PAU uses multiple plugins to
find a principal. If the first authenticator plugin can't find the requested
principal, the next plugin is used, and so on.
To illustrate, we'll create and register a second searchable authenticator::
>>> searchable2 = SearchableAuthenticatorPlugin()
>>> provideUtility(searchable2, name='Searchable Authentication Plugin 2')
and add a principal to it::
>>> searchable.add('black', 'Black Spy', 'Also sneaky', 'deathtowhite')
When we configure the PAU to use both searchable authenticators (note the
order)::
>>> pau.authenticatorPlugins = (
... 'Searchable Authentication Plugin 2',
... 'Searchable Authentication Plugin')
we see how the PAU uses both plugins::
>>> pau.getPrincipal('xyz_white')
Principal('xyz_white')
>>> pau.getPrincipal('xyz_black')
Principal('xyz_black')
If more than one plugin know about the same principal ID, the first plugin is
used and the remaining are not delegated to. To illustrate, we'll add
another principal with the same ID as an existing principal::
>>> searchable2.add('white', 'White Rider', '', 'r1der')
>>> pau.getPrincipal('xyz_white').title
'White Rider'
If we change the order of the plugins::
>>> pau.authenticatorPlugins = (
... 'Searchable Authentication Plugin',
... 'Searchable Authentication Plugin 2')
we get a different principal for ID 'white'::
>>> pau.getPrincipal('xyz_white').title
'White Spy'
Issuing a Challenge
-------------------
Part of PAU's IAuthentication contract is to challenge the user for
credentials when its 'unauthorized' method is called. The need for this
functionality is driven by the following use case:
- A user attempts to perform an operation he is not authorized to perform.
- A handler responds to the unauthorized error by calling IAuthentication
'unauthorized'.
- The authentication component (in our case, a PAU) issues a challenge to
the user to collect new credentials (typically in the form of logging in
as a new user).
The PAU handles the credentials challenge by delegating to its credentials
plugins.
Currently, the PAU is configured with the credentials plugins that don't
perform any action when asked to challenge (see above the 'challenge' methods).
To illustrate challenges, we'll subclass an existing credentials plugin and
do something in its 'challenge'::
>>> class LoginFormCredentialsPlugin(FormCredentialsPlugin):
...
... def __init__(self, loginForm):
... self.loginForm = loginForm
...
... def challenge(self, request):
... request.response.redirect(self.loginForm)
... return True
This plugin handles a challenge by redirecting the response to a login form.
It returns True to signal to the PAU that it handled the challenge.
We will now create and register a couple of these plugins::
>>> provideUtility(LoginFormCredentialsPlugin('simplelogin.html'),
... name='Simple Login Form Plugin')
>>> provideUtility(LoginFormCredentialsPlugin('advancedlogin.html'),
... name='Advanced Login Form Plugin')
and configure the PAU to use them::
>>> pau.credentialsPlugins = (
... 'Simple Login Form Plugin',
... 'Advanced Login Form Plugin')
Now when we call 'unauthorized' on the PAU::
>>> request = TestRequest()
>>> pau.unauthorized(id=None, request=request)
we see that the user is redirected to the simple login form::
>>> request.response.getStatus()
302
>>> request.response.getHeader('location')
'simplelogin.html'
We can change the challenge policy by reordering the plugins::
>>> pau.credentialsPlugins = (
... 'Advanced Login Form Plugin',
... 'Simple Login Form Plugin')
Now when we call 'unauthorized'::
>>> request = TestRequest()
>>> pau.unauthorized(id=None, request=request)
the advanced plugin is used because it's first::
>>> request.response.getStatus()
302
>>> request.response.getHeader('location')
'advancedlogin.html'
Challenge Protocols
~~~~~~~~~~~~~~~~~~~
Sometimes, we want multiple challengers to work together. For example, the
HTTP specification allows multiple challenges to be issued in a response. A
challenge plugin can provide a `challengeProtocol` attribute that effectively
groups related plugins together for challenging. If a plugin returns `True`
from its challenge and provides a non-None challengeProtocol, subsequent
plugins in the credentialsPlugins list that have the same challenge protocol
will also be used to challenge.
Without a challengeProtocol, only the first plugin to succeed in a challenge
will be used.
Let's look at an example. We'll define a new plugin that specifies an
'X-Challenge' protocol::
>>> class XChallengeCredentialsPlugin(FormCredentialsPlugin):
...
... challengeProtocol = 'X-Challenge'
...
... def __init__(self, challengeValue):
... self.challengeValue = challengeValue
...
... def challenge(self, request):
... value = self.challengeValue
... existing = request.response.getHeader('X-Challenge', '')
... if existing:
... value += ' ' + existing
... request.response.setHeader('X-Challenge', value)
... return True
and register a couple instances as utilities::
>>> provideUtility(XChallengeCredentialsPlugin('basic'),
... name='Basic X-Challenge Plugin')
>>> provideUtility(XChallengeCredentialsPlugin('advanced'),
... name='Advanced X-Challenge Plugin')
When we use both plugins with the PAU::
>>> pau.credentialsPlugins = (
... 'Basic X-Challenge Plugin',
... 'Advanced X-Challenge Plugin')
and call 'unauthorized'::
>>> request = TestRequest()
>>> pau.unauthorized(None, request)
we see that both plugins participate in the challange, rather than just the
first plugin::
>>> request.response.getHeader('X-Challenge')
'advanced basic'
Pluggable-Authentication Prefixes
---------------------------------
Principal ids are required to be unique system wide. Plugins will often provide
options for providing id prefixes, so that different sets of plugins provide
unique ids within a PAU. If there are multiple pluggable-authentication
utilities in a system, it's a good idea to give each PAU a unique prefix, so
that principal ids from different PAUs don't conflict. We can provide a prefix
when a PAU is created::
>>> pau = authentication.PluggableAuthentication('mypau_')
>>> pau.credentialsPlugins = ('My Credentials Plugin', )
>>> pau.authenticatorPlugins = ('My Authenticator Plugin', )
When we create a request and try to authenticate::
>>> pau.authenticate(TestRequest(credentials='secretcode'))
Principal('mypau_bob')
Note that now, our principal's id has the pluggable-authentication
utility prefix.
We can still lookup a principal, as long as we supply the prefix::
>> pau.getPrincipal('mypas_42')
Principal('mypas_42', "{'domain': 42}")
>> pau.getPrincipal('mypas_41')
OddPrincipal('mypas_41', "{'int': 41}")
Searching
---------
PAU implements ISourceQueriables::
>>> from zope.schema.interfaces import ISourceQueriables
>>> ISourceQueriables.providedBy(pau)
True
This means a PAU can be used in a principal source vocabulary (Zope provides a
sophisticated searching UI for principal sources).
As we've seen, a PAU uses each of its authenticator plugins to locate a
principal with a given ID. However, plugins may also provide the interface
IQuerySchemaSearch to indicate they can be used in the PAU's principal search
scheme.
Currently, our list of authenticators::
>>> pau.authenticatorPlugins
('My Authenticator Plugin',)
does not include a queriable authenticator. PAU cannot therefore provide any
queriables::
>>> list(pau.getQueriables())
[]
Before we illustrate how an authenticator is used by the PAU to search for
principals, we need to setup an adapter used by PAU::
>>> import zope.app.authentication.authentication
>>> provideAdapter(
... authentication.authentication.QuerySchemaSearchAdapter,
... provides=interfaces.IQueriableAuthenticator)
This adapter delegates search responsibility to an authenticator, but prepends
the PAU prefix to any principal IDs returned in a search.
Next, we'll create a plugin that provides a search interface::
>>> @interface.implementer(interfaces.IQuerySchemaSearch)
... class QueriableAuthenticatorPlugin(MyAuthenticatorPlugin):
...
... schema = None
...
... def search(self, query, start=None, batch_size=None):
... yield 'foo'
...
and install it as a plugin::
>>> plugin = QueriableAuthenticatorPlugin()
>>> provideUtility(plugin,
... provides=interfaces.IAuthenticatorPlugin,
... name='Queriable')
>>> pau.authenticatorPlugins += ('Queriable',)
Now, the PAU provides a single queriable::
>>> list(pau.getQueriables()) # doctest: +ELLIPSIS
[('Queriable', ...QuerySchemaSearchAdapter object...)]
We can use this queriable to search for our principal::
>>> queriable = list(pau.getQueriables())[0][1]
>>> list(queriable.search('not-used'))
['mypau_foo']
Note that the resulting principal ID includes the PAU prefix. Were we to search
the plugin directly::
>>> list(plugin.search('not-used'))
['foo']
The result does not include the PAU prefix. The prepending of the prefix is
handled by the PluggableAuthenticationQueriable.
Queryiable plugins can provide the ILocation interface. In this case the
QuerySchemaSearchAdapter's __parent__ is the same as the __parent__ of the
plugin::
>>> import zope.location.interfaces
>>> @interface.implementer(zope.location.interfaces.ILocation)
... class LocatedQueriableAuthenticatorPlugin(QueriableAuthenticatorPlugin):
...
... __parent__ = __name__ = None
...
>>> import zope.component.hooks
>>> site = zope.component.hooks.getSite()
>>> plugin = LocatedQueriableAuthenticatorPlugin()
>>> plugin.__parent__ = site
>>> plugin.__name__ = 'localname'
>>> provideUtility(plugin,
... provides=interfaces.IAuthenticatorPlugin,
... name='location-queriable')
>>> pau.authenticatorPlugins = ('location-queriable',)
We have one queriable again::
>>> queriables = list(pau.getQueriables())
>>> queriables # doctest: +ELLIPSIS
[('location-queriable', ...QuerySchemaSearchAdapter object...)]
The queriable's __parent__ is the site as set above::
>>> queriable = queriables[0][1]
>>> queriable.__parent__ is site
True
If the queriable provides ILocation but is not actually locatable (i.e. the
parent is None) the pau itself becomes the parent::
>>> plugin = LocatedQueriableAuthenticatorPlugin()
>>> provideUtility(plugin,
... provides=interfaces.IAuthenticatorPlugin,
... name='location-queriable-wo-parent')
>>> pau.authenticatorPlugins = ('location-queriable-wo-parent',)
We have one queriable again::
>>> queriables = list(pau.getQueriables())
>>> queriables # doctest: +ELLIPSIS
[('location-queriable-wo-parent', ...QuerySchemaSearchAdapter object...)]
And the parent is the pau::
>>> queriable = queriables[0][1]
>>> queriable.__parent__ # doctest: +ELLIPSIS
<zope.pluggableauth.authentication.PluggableAuthentication object ...>
>>> queriable.__parent__ is pau
True
================
Principal Folder
================
Principal folders contain principal-information objects that contain principal
information. We create an internal principal using the `InternalPrincipal`
class:
>>> from zope.app.authentication.principalfolder import InternalPrincipal
>>> p1 = InternalPrincipal('login1', '123', "Principal 1",
... passwordManagerName="SHA1")
>>> p2 = InternalPrincipal('login2', '456', "The Other One")
and add them to a principal folder:
>>> from zope.app.authentication.principalfolder import PrincipalFolder
>>> principals = PrincipalFolder('principal.')
>>> principals['p1'] = p1
>>> principals['p2'] = p2
Authentication
--------------
Principal folders provide the `IAuthenticatorPlugin` interface. When we
provide suitable credentials:
>>> from pprint import pprint
>>> principals.authenticateCredentials({'login': 'login1', 'password': '123'})
PrincipalInfo(u'principal.p1')
We get back a principal id and supplementary information, including the
principal title and description. Note that the principal id is a concatenation
of the principal-folder prefix and the name of the principal-information object
within the folder.
None is returned if the credentials are invalid:
>>> principals.authenticateCredentials({'login': 'login1',
... 'password': '1234'})
>>> principals.authenticateCredentials(42)
Search
------
Principal folders also provide the IQuerySchemaSearch interface. This
supports both finding principal information based on their ids:
>>> principals.principalInfo('principal.p1')
PrincipalInfo('principal.p1')
>>> principals.principalInfo('p1')
and searching for principals based on a search string:
>>> list(principals.search({'search': 'other'}))
[u'principal.p2']
>>> list(principals.search({'search': 'OTHER'}))
[u'principal.p2']
>>> list(principals.search({'search': ''}))
[u'principal.p1', u'principal.p2']
>>> list(principals.search({'search': 'eek'}))
[]
>>> list(principals.search({}))
[]
If there are a large number of matches:
>>> for i in range(20):
... i = str(i)
... p = InternalPrincipal('l'+i, i, "Dude "+i)
... principals[i] = p
>>> pprint(list(principals.search({'search': 'D'})))
[u'principal.0',
u'principal.1',
u'principal.10',
u'principal.11',
u'principal.12',
u'principal.13',
u'principal.14',
u'principal.15',
u'principal.16',
u'principal.17',
u'principal.18',
u'principal.19',
u'principal.2',
u'principal.3',
u'principal.4',
u'principal.5',
u'principal.6',
u'principal.7',
u'principal.8',
u'principal.9']
We can use batching parameters to specify a subset of results:
>>> pprint(list(principals.search({'search': 'D'}, start=17)))
[u'principal.7', u'principal.8', u'principal.9']
>>> pprint(list(principals.search({'search': 'D'}, batch_size=5)))
[u'principal.0',
u'principal.1',
u'principal.10',
u'principal.11',
u'principal.12']
>>> pprint(list(principals.search({'search': 'D'}, start=5, batch_size=5)))
[u'principal.13',
u'principal.14',
u'principal.15',
u'principal.16',
u'principal.17']
There is an additional method that allows requesting the principal id
associated with a login id. The method raises KeyError when there is
no associated principal::
>>> principals.getIdByLogin("not-there")
Traceback (most recent call last):
KeyError: 'not-there'
If there is a matching principal, the id is returned::
>>> principals.getIdByLogin("login1")
u'principal.p1'
Changing credentials
--------------------
Credentials can be changed by modifying principal-information objects:
>>> p1.login = 'bob'
>>> p1.password = 'eek'
>>> principals.authenticateCredentials({'login': 'bob', 'password': 'eek'})
PrincipalInfo(u'principal.p1')
>>> principals.authenticateCredentials({'login': 'login1',
... 'password': 'eek'})
>>> principals.authenticateCredentials({'login': 'bob',
... 'password': '123'})
It is an error to try to pick a login name that is already taken:
>>> p1.login = 'login2'
Traceback (most recent call last):
...
ValueError: Principal Login already taken!
If such an attempt is made, the data are unchanged:
>>> principals.authenticateCredentials({'login': 'bob', 'password': 'eek'})
PrincipalInfo(u'principal.p1')
Removing principals
-------------------
Of course, if a principal is removed, we can no-longer authenticate it:
>>> del principals['p1']
>>> principals.authenticateCredentials({'login': 'bob',
... 'password': 'eek'})
============
Vocabularies
============
The vocabulary module provides vocabularies for the authenticator plugins and
the credentials plugins.
The options should include the unique names of all of the plugins that provide
the appropriate interface (interfaces.ICredentialsPlugin or
interfaces.IAuthentiatorPlugin, respectively) for the current context-- which
is expected to be a pluggable authentication utility, hereafter referred to as
a PAU.
These names may be for objects contained within the PAU ("contained
plugins"), or may be utilities registered for the specified interface,
found in the context of the PAU ("utility plugins"). Contained
plugins mask utility plugins of the same name. They also may be names
currently selected in the PAU that do not actually have a
corresponding plugin at this time.
Here is a short example of how the vocabulary should work. Let's say we're
working with authentication plugins. We'll create some faux
authentication plugins, and register some of them as utilities and put
others in a faux PAU.
>>> from zope.app.authentication import interfaces
>>> from zope import interface, component
>>> @interface.implementer(interfaces.IAuthenticatorPlugin)
... class DemoPlugin(object):
...
... def __init__(self, name):
... self.name = name
...
>>> utility_plugins = dict(
... (i, DemoPlugin(u'Plugin %d' % i)) for i in range(4))
>>> contained_plugins = dict(
... (i, DemoPlugin(u'Plugin %d' % i)) for i in range(1, 5))
>>> sorted(utility_plugins.keys())
[0, 1, 2, 3]
>>> for p in utility_plugins.values():
... component.provideUtility(p, name=p.name)
...
>>> sorted(contained_plugins.keys()) # 1 will mask utility plugin 1
[1, 2, 3, 4]
>>> @interface.implementer(interfaces.IPluggableAuthentication)
... class DemoAuth(dict):
...
... def __init__(self, *args, **kwargs):
... super(DemoAuth, self).__init__(*args, **kwargs)
... self.authenticatorPlugins = (u'Plugin 3', u'Plugin X')
... self.credentialsPlugins = (u'Plugin 4', u'Plugin X')
...
>>> auth = DemoAuth((p.name, p) for p in contained_plugins.values())
>>> @component.adapter(interface.Interface)
... @interface.implementer(component.IComponentLookup)
... def getSiteManager(context):
... return component.getGlobalSiteManager()
...
>>> component.provideAdapter(getSiteManager)
We are now ready to create a vocabulary that we can use. The context is
our faux authentication utility, `auth`.
>>> from zope.app.authentication import vocabulary
>>> vocab = vocabulary.authenticatorPlugins(auth)
Iterating over the vocabulary results in all of the terms, in a relatively
arbitrary order of their names. (This vocabulary should typically use a
widget that sorts values on the basis of localized collation order of the
term titles.)
>>> [term.value for term in vocab] # doctest: +NORMALIZE_WHITESPACE
[u'Plugin 0', u'Plugin 1', u'Plugin 2', u'Plugin 3', u'Plugin 4',
u'Plugin X']
Similarly, we can use `in` to test for the presence of values in the
vocabulary.
>>> ['Plugin %s' % i in vocab for i in range(-1, 6)]
[False, True, True, True, True, True, False]
>>> 'Plugin X' in vocab
True
The length reports the expected value.
>>> len(vocab)
6
One can get a term for a given value using `getTerm()`; its token, in
turn, should also return the same effective term from `getTermByToken`.
>>> values = ['Plugin 0', 'Plugin 1', 'Plugin 2', 'Plugin 3', 'Plugin 4',
... 'Plugin X']
>>> for val in values:
... term = vocab.getTerm(val)
... assert term.value == val
... term2 = vocab.getTermByToken(term.token)
... assert term2.token == term.token
... assert term2.value == val
...
The terms have titles, which are message ids that show the plugin title or id
and whether the plugin is a utility or just contained in the auth utility.
We'll give one of the plugins a dublin core title just to show the
functionality.
>>> import zope.dublincore.interfaces
>>> class ISpecial(interface.Interface):
... pass
...
>>> interface.directlyProvides(contained_plugins[1], ISpecial)
>>> @interface.implementer(zope.dublincore.interfaces.IDCDescriptiveProperties)
... @component.adapter(ISpecial)
... class DemoDCAdapter(object):
... def __init__(self, context):
... pass
... title = u'Special Title'
...
>>> component.provideAdapter(DemoDCAdapter)
We need to regenerate the vocabulary, since it calculates all of its data at
once.
>>> vocab = vocabulary.authenticatorPlugins(auth)
Now we'll check the titles. We'll have to translate them to see what we
expect.
>>> from zope import i18n
>>> import pprint
>>> pprint.pprint([i18n.translate(term.title) for term in vocab])
[u'Plugin 0 (a utility)',
u'Special Title (in contents)',
u'Plugin 2 (in contents)',
u'Plugin 3 (in contents)',
u'Plugin 4 (in contents)',
u'Plugin X (not found; deselecting will remove)']
credentialsPlugins
------------------
For completeness, we'll do the same review of the credentialsPlugins.
>>> @interface.implementer(interfaces.ICredentialsPlugin)
... class DemoPlugin(object):
...
... def __init__(self, name):
... self.name = name
...
>>> utility_plugins = dict(
... (i, DemoPlugin(u'Plugin %d' % i)) for i in range(4))
>>> contained_plugins = dict(
... (i, DemoPlugin(u'Plugin %d' % i)) for i in range(1, 5))
>>> for p in utility_plugins.values():
... component.provideUtility(p, name=p.name)
...
>>> auth = DemoAuth((p.name, p) for p in contained_plugins.values())
>>> vocab = vocabulary.credentialsPlugins(auth)
Iterating over the vocabulary results in all of the terms, in a relatively
arbitrary order of their names. (This vocabulary should typically use a
widget that sorts values on the basis of localized collation order of the term
titles.) Similarly, we can use `in` to test for the presence of values in the
vocabulary. The length reports the expected value.
>>> [term.value for term in vocab] # doctest: +NORMALIZE_WHITESPACE
[u'Plugin 0', u'Plugin 1', u'Plugin 2', u'Plugin 3', u'Plugin 4',
u'Plugin X']
>>> ['Plugin %s' % i in vocab for i in range(-1, 6)]
[False, True, True, True, True, True, False]
>>> 'Plugin X' in vocab
True
>>> len(vocab)
6
One can get a term for a given value using `getTerm()`; its token, in
turn, should also return the same effective term from `getTermByToken`.
>>> values = ['Plugin 0', 'Plugin 1', 'Plugin 2', 'Plugin 3', 'Plugin 4',
... 'Plugin X']
>>> for val in values:
... term = vocab.getTerm(val)
... assert term.value == val
... term2 = vocab.getTermByToken(term.token)
... assert term2.token == term.token
... assert term2.value == val
...
The terms have titles, which are message ids that show the plugin title or id
and whether the plugin is a utility or just contained in the auth utility.
We'll give one of the plugins a dublin core title just to show the
functionality. We need to regenerate the vocabulary, since it calculates all
of its data at once. Then we'll check the titles. We'll have to translate
them to see what we expect.
>>> interface.directlyProvides(contained_plugins[1], ISpecial)
>>> vocab = vocabulary.credentialsPlugins(auth)
>>> pprint.pprint([i18n.translate(term.title) for term in vocab])
[u'Plugin 0 (a utility)',
u'Special Title (in contents)',
u'Plugin 2 (in contents)',
u'Plugin 3 (in contents)',
u'Plugin 4 (in contents)',
u'Plugin X (not found; deselecting will remove)']
=======
Changes
=======
6.0 (2025-09-12)
----------------
* Replace ``pkg_resources`` namespace with PEP 420 native namespace.
* Drop support for Python 3.8.
5.1 (2024-11-29)
----------------
- Add support for Python 3.12, 3.13.
- Drop support for Python 3.7.
- Fix tests to support multipart 1.x+ versions.
5.0 (2023-02-09)
----------------
- Drop support for Python 2.7, 3.3, 3.4, 3.5, 3.6.
- Add support for Python 3.7, 3.8, 3.9, 3.10, 3.11.
4.0.0 (2017-05-02)
------------------
- Drop test dependency on zope.app.zcmlfiles and zope.app.testing.
- Drop explicit dependency on ZODB3.
- Add support for Python 3.4, 3.5 and 3.6, and PyPy.
3.9 (2010-10-18)
----------------
* Move concrete IAuthenticatorPlugin implementations to
zope.pluggableauth.plugins. Leave backwards compatibility imports.
* Use zope.formlib throughout to lift the dependency on zope.app.form. As it
turns out, zope.app.form is still a indirect test dependency though.
3.8.0 (2010-09-25)
------------------
* Using python's ``doctest`` module instead of deprecated
``zope.testing.doctest[unit]``.
* Moved the following views from `zope.app.securitypolicy` here, to inverse
dependency between these two packages, as `zope.app.securitypolicy`
deprecated in ZTK 1.0:
- ``@@grant.html``
- ``@@AllRolePermissions.html``
- ``@@RolePermissions.html``
- ``@@RolesWithPermission.html``
3.7.1 (2010-02-11)
------------------
* Using the new `principalfactories.zcml` file, from ``zope.pluggableauth``,
to avoid duplication errors, in the adapters registration.
3.7.0 (2010-02-08)
------------------
* The Pluggable Authentication utility has been severed and released
in a standalone package: `zope.pluggableauth`. We are now using this
new package, providing backward compatibility imports to assure a
smooth transition.
3.6.2 (2010-01-05)
------------------
* Fix tests by using zope.login, and require new zope.publisher 3.12.
3.6.1 (2009-10-07)
------------------
* Fix ftesting.zcml due to ``zope.securitypolicy`` update.
* Don't use ``zope.app.testing.ztapi`` in tests, use zope.component's
testing functions instead.
* Fix functional tests and stop using port 8081. Redirecting to
different port without trusted flag is not allowed.
3.6.0 (2009-03-14)
------------------
* Separate the presentation template and camefrom/redirection logic for the
``loginForm.html`` view. Now the logic is contained in the
``zope.app.authentication.browser.loginform.LoginForm`` class.
* Fix login form redirection failure in some cases with Python 2.6.
* Use the new ``zope.authentication`` package instead of ``zope.app.security``.
* The "Password Manager Names" vocabulary and simple password manager registry
were moved to the ``zope.password`` package.
* Remove deprecated code.
3.5.0 (2009-03-06)
------------------
* Split password manager functionality off to the new ``zope.password``
package. Backward-compatibility imports are left in place.
* Use ``zope.site`` instead of ``zope.app.component``. (Browser code still
needs ``zope.app.component`` as it depends on view classes of this
package.)
3.5.0a2 (2009-02-01)
--------------------
* Make old encoded passwords really work.
3.5.0a1 (2009-01-31)
--------------------
* Use ``zope.container`` instead of ``zope.app.container``. (Browser code
still needs ``zope.app.container`` as it depends on view classes of this
package.)
* Encoded passwords are now stored with a prefix ({MD5}, {SHA1},
{SSHA}) indicating the used encoding schema. Old (encoded) passwords
can still be used.
* Add an SSHA password manager that is compatible with standard LDAP
passwords. As this encoding gives better security agains dictionary
attacks, users are encouraged to switch to this new password schema.
* InternalPrincipal now uses SSHA password manager by default.
3.4.4 (2008-12-12)
------------------
* Depend on zope.session instead of zope.app.session. The first one
currently has all functionality we need.
* Fix deprecation warnings for ``md5`` and ``sha`` on Python 2.6.
3.4.3 (2008-08-07)
------------------
* No changes. Retag for correct release on PyPI.
3.4.2 (2008-07-09)
-------------------
* Make it compatible with zope.app.container 3.6.1 and 3.5.4 changes,
Changed ``super(BTreeContainer, self).__init__()`` to
``super(GroupFolder, self).__init__()`` in ``GroupFolder`` class.
3.4.1 (2007-10-24)
------------------
* Avoid deprecation warning.
3.4.0 (2007-10-11)
------------------
* Updated package meta-data.
3.4.0b1 (2007-09-27)
--------------------
* First release independent of Zope.
Raw data
{
"_id": null,
"home_page": "http://github.com/zopefoundation/zope.app.authentication",
"name": "zope.app.authentication",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.9",
"maintainer_email": null,
"keywords": "zope3 authentication pluggable principal group",
"author": "Zope Foundation and Contributors",
"author_email": "zope-dev@zope.dev",
"download_url": "https://files.pythonhosted.org/packages/81/07/f7b02a13eda3775d7e63ecd33fe7b1138b9dcdfff69998e0c9c7a2925958/zope_app_authentication-6.0.tar.gz",
"platform": null,
"description": "This package provides a flexible and pluggable authentication utility for Zope\n3, using `zope.pluggableauth`. Several common plugins are provided.\n\n\n.. contents::\n\n================================\nPluggable-Authentication Utility\n================================\n\nThe Pluggable-Authentication Utility (PAU) provides a framework for\nauthenticating principals and associating information with them. It uses\nplugins and subscribers to get its work done.\n\nFor a pluggable-authentication utility to be used, it should be\nregistered as a utility providing the\n`zope.authentication.interfaces.IAuthentication` interface.\n\nAuthentication\n--------------\n\nThe primary job of PAU is to authenticate principals. It uses two types of\nplug-ins in its work:\n\n - Credentials Plugins\n\n - Authenticator Plugins\n\nCredentials plugins are responsible for extracting user credentials from a\nrequest. A credentials plugin may in some cases issue a 'challenge' to obtain\ncredentials. For example, a 'session' credentials plugin reads credentials\nfrom a session (the \"extraction\"). If it cannot find credentials, it will\nredirect the user to a login form in order to provide them (the \"challenge\").\n\nAuthenticator plugins are responsible for authenticating the credentials\nextracted by a credentials plugin. They are also typically able to create\nprincipal objects for credentials they successfully authenticate.\n\nGiven a request object, the PAU returns a principal object, if it can. The PAU\ndoes this by first iterateing through its credentials plugins to obtain a\nset of credentials. If it gets credentials, it iterates through its\nauthenticator plugins to authenticate them.\n\nIf an authenticator succeeds in authenticating a set of credentials, the PAU\nuses the authenticator to create a principal corresponding to the credentials.\nThe authenticator notifies subscribers if an authenticated principal is\ncreated. Subscribers are responsible for adding data, especially groups, to\nthe principal. Typically, if a subscriber adds data, it should also add\ncorresponding interface declarations.\n\nSimple Credentials Plugin\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\nTo illustrate, we'll create a simple credentials plugin::\n\n >>> from zope import interface\n >>> from zope.app.authentication import interfaces\n\n >>> @interface.implementer(interfaces.ICredentialsPlugin)\n ... class MyCredentialsPlugin(object):\n ...\n ...\n ... def extractCredentials(self, request):\n ... return request.get('credentials')\n ...\n ... def challenge(self, request):\n ... pass # challenge is a no-op for this plugin\n ...\n ... def logout(self, request):\n ... pass # logout is a no-op for this plugin\n\nAs a plugin, MyCredentialsPlugin needs to be registered as a named utility::\n\n >>> myCredentialsPlugin = MyCredentialsPlugin()\n >>> provideUtility(myCredentialsPlugin, name='My Credentials Plugin')\n\nSimple Authenticator Plugin\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nNext we'll create a simple authenticator plugin. For our plugin, we'll need\nan implementation of IPrincipalInfo::\n\n >>> @interface.implementer(interfaces.IPrincipalInfo)\n ... class PrincipalInfo(object):\n ...\n ... def __init__(self, id, title, description):\n ... self.id = id\n ... self.title = title\n ... self.description = description\n ...\n ... def __repr__(self):\n ... return 'PrincipalInfo(%r)' % self.id\n\nOur authenticator uses this type when it creates a principal info::\n\n >>> @interface.implementer(interfaces.IAuthenticatorPlugin)\n ... class MyAuthenticatorPlugin(object):\n ...\n ... def authenticateCredentials(self, credentials):\n ... if credentials == 'secretcode':\n ... return PrincipalInfo('bob', 'Bob', '')\n ...\n ... def principalInfo(self, id):\n ... pass # plugin not currently supporting search\n\nAs with the credentials plugin, the authenticator plugin must be registered\nas a named utility::\n\n >>> myAuthenticatorPlugin = MyAuthenticatorPlugin()\n >>> provideUtility(myAuthenticatorPlugin, name='My Authenticator Plugin')\n\nPrincipal Factories\n~~~~~~~~~~~~~~~~~~~\n\nWhile authenticator plugins provide principal info, they are not responsible\nfor creating principals. This function is performed by factory adapters. For\nthese tests we'll borrow some factories from the principal folder::\n\n >>> from zope.app.authentication import principalfolder\n >>> provideAdapter(principalfolder.AuthenticatedPrincipalFactory)\n >>> provideAdapter(principalfolder.FoundPrincipalFactory)\n\nFor more information on these factories, see their docstrings.\n\nConfiguring a PAU\n~~~~~~~~~~~~~~~~~\n\nFinally, we'll create the PAU itself::\n\n >>> from zope.app import authentication\n >>> pau = authentication.PluggableAuthentication('xyz_')\n\nand configure it with the two plugins::\n\n >>> pau.credentialsPlugins = ('My Credentials Plugin', )\n >>> pau.authenticatorPlugins = ('My Authenticator Plugin', )\n\nUsing the PAU to Authenticate\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWe can now use the PAU to authenticate a sample request::\n\n >>> from zope.publisher.browser import TestRequest\n >>> print(pau.authenticate(TestRequest()))\n None\n\nIn this case, we cannot authenticate an empty request. In the same way, we\nwill not be able to authenticate a request with the wrong credentials::\n\n >>> print(pau.authenticate(TestRequest(credentials='let me in!')))\n None\n\nHowever, if we provide the proper credentials::\n\n >>> request = TestRequest(credentials='secretcode')\n >>> principal = pau.authenticate(request)\n >>> principal\n Principal('xyz_bob')\n\nwe get an authenticated principal.\n\nAuthenticated Principal Creates Events\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWe can verify that the appropriate event was published::\n\n >>> [event] = getEvents(interfaces.IAuthenticatedPrincipalCreated)\n >>> event.principal is principal\n True\n >>> event.info\n PrincipalInfo('bob')\n >>> event.request is request\n True\n\nThe info object has the id, title, and description of the principal. The info\nobject is also generated by the authenticator plugin, so the plugin may\nitself have provided additional information on the info object::\n\n >>> event.info.title\n 'Bob'\n >>> event.info.id # does not include pau prefix\n 'bob'\n >>> event.info.description\n ''\n\nIt is also decorated with two other attributes, credentialsPlugin and\nauthenticatorPlugin: these are the plugins used to extract credentials for and\nauthenticate this principal. These attributes can be useful for subscribers\nthat want to react to the plugins used. For instance, subscribers can\ndetermine that a given credential plugin does or does not support logout, and\nprovide information usable to show or hide logout user interface::\n\n >>> event.info.credentialsPlugin is myCredentialsPlugin\n True\n >>> event.info.authenticatorPlugin is myAuthenticatorPlugin\n True\n\nNormally, we provide subscribers to these events that add additional\ninformation to the principal. For example, we'll add one that sets\nthe title::\n\n >>> def add_info(event):\n ... event.principal.title = event.info.title\n >>> provideHandler(add_info, [interfaces.IAuthenticatedPrincipalCreated])\n\nNow, if we authenticate a principal, its title is set::\n\n >>> principal = pau.authenticate(request)\n >>> principal.title\n 'Bob'\n\nMultiple Authenticator Plugins\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe PAU works with multiple authenticator plugins. It uses each plugin, in the\norder specified in the PAU's authenticatorPlugins attribute, to authenticate\na set of credentials.\n\nTo illustrate, we'll create another authenticator::\n\n >>> class MyAuthenticatorPlugin2(MyAuthenticatorPlugin):\n ...\n ... def authenticateCredentials(self, credentials):\n ... if credentials == 'secretcode':\n ... return PrincipalInfo('black', 'Black Spy', '')\n ... elif credentials == 'hiddenkey':\n ... return PrincipalInfo('white', 'White Spy', '')\n\n >>> provideUtility(MyAuthenticatorPlugin2(), name='My Authenticator Plugin 2')\n\nIf we put it before the original authenticator::\n\n >>> pau.authenticatorPlugins = (\n ... 'My Authenticator Plugin 2',\n ... 'My Authenticator Plugin')\n\nThen it will be given the first opportunity to authenticate a request::\n\n >>> pau.authenticate(TestRequest(credentials='secretcode'))\n Principal('xyz_black')\n\nIf neither plugins can authenticate, pau returns None::\n\n >>> print(pau.authenticate(TestRequest(credentials='let me in!!')))\n None\n\nWhen we change the order of the authenticator plugins::\n\n >>> pau.authenticatorPlugins = (\n ... 'My Authenticator Plugin',\n ... 'My Authenticator Plugin 2')\n\nwe see that our original plugin is now acting first::\n\n >>> pau.authenticate(TestRequest(credentials='secretcode'))\n Principal('xyz_bob')\n\nThe second plugin, however, gets a chance to authenticate if first does not::\n\n >>> pau.authenticate(TestRequest(credentials='hiddenkey'))\n Principal('xyz_white')\n\nMultiple Credentials Plugins\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAs with with authenticators, we can specify multiple credentials plugins. To\nillustrate, we'll create a credentials plugin that extracts credentials from\na request form::\n\n >>> @interface.implementer(interfaces.ICredentialsPlugin)\n ... class FormCredentialsPlugin:\n ...\n ... def extractCredentials(self, request):\n ... return request.form.get('my_credentials')\n ...\n ... def challenge(self, request):\n ... pass\n ...\n ... def logout(request):\n ... pass\n\n >>> provideUtility(FormCredentialsPlugin(),\n ... name='Form Credentials Plugin')\n\nand insert the new credentials plugin before the existing plugin::\n\n >>> pau.credentialsPlugins = (\n ... 'Form Credentials Plugin',\n ... 'My Credentials Plugin')\n\nThe PAU will use each plugin in order to try and obtain credentials from a\nrequest::\n\n >>> pau.authenticate(TestRequest(credentials='secretcode',\n ... form={'my_credentials': 'hiddenkey'}))\n Principal('xyz_white')\n\nIn this case, the first credentials plugin succeeded in getting credentials\nfrom the form and the second authenticator was able to authenticate the\ncredentials. Specifically, the PAU went through these steps:\n\n - Get credentials using 'Form Credentials Plugin'\n\n - Got 'hiddenkey' credentials using 'Form Credentials Plugin', try to\n authenticate using 'My Authenticator Plugin'\n\n - Failed to authenticate 'hiddenkey' with 'My Authenticator Plugin', try\n 'My Authenticator Plugin 2'\n\n - Succeeded in authenticating with 'My Authenticator Plugin 2'\n\nLet's try a different scenario::\n\n >>> pau.authenticate(TestRequest(credentials='secretcode'))\n Principal('xyz_bob')\n\nIn this case, the PAU went through these steps::\n\n - Get credentials using 'Form Credentials Plugin'\n\n - Failed to get credentials using 'Form Credentials Plugin', try\n 'My Credentials Plugin'\n\n - Got 'scecretcode' credentials using 'My Credentials Plugin', try to\n authenticate using 'My Authenticator Plugin'\n\n - Succeeded in authenticating with 'My Authenticator Plugin'\n\nLet's try a slightly more complex scenario::\n\n >>> pau.authenticate(TestRequest(credentials='hiddenkey',\n ... form={'my_credentials': 'bogusvalue'}))\n Principal('xyz_white')\n\nThis highlights PAU's ability to use multiple plugins for authentication:\n\n - Get credentials using 'Form Credentials Plugin'\n\n - Got 'bogusvalue' credentials using 'Form Credentials Plugin', try to\n authenticate using 'My Authenticator Plugin'\n\n - Failed to authenticate 'boguskey' with 'My Authenticator Plugin', try\n 'My Authenticator Plugin 2'\n\n - Failed to authenticate 'boguskey' with 'My Authenticator Plugin 2' --\n there are no more authenticators to try, so lets try the next credentials\n plugin for some new credentials\n\n - Get credentials using 'My Credentials Plugin'\n\n - Got 'hiddenkey' credentials using 'My Credentials Plugin', try to\n authenticate using 'My Authenticator Plugin'\n\n - Failed to authenticate 'hiddenkey' using 'My Authenticator Plugin', try\n 'My Authenticator Plugin 2'\n\n - Succeeded in authenticating with 'My Authenticator Plugin 2' (shouts and\n cheers!)\n\n\nPrincipal Searching\n-------------------\n\nAs a component that provides IAuthentication, a PAU lets you lookup a\nprincipal with a principal ID. The PAU looks up a principal by delegating to\nits authenticators. In our example, none of the authenticators implement this\nsearch capability, so when we look for a principal::\n\n >>> print(pau.getPrincipal('xyz_bob'))\n Traceback (most recent call last):\n zope.authentication.interfaces.PrincipalLookupError: bob\n\n >>> print(pau.getPrincipal('white'))\n Traceback (most recent call last):\n zope.authentication.interfaces.PrincipalLookupError: white\n\n >>> print(pau.getPrincipal('black'))\n Traceback (most recent call last):\n zope.authentication.interfaces.PrincipalLookupError: black\n\nFor a PAU to support search, it needs to be configured with one or more\nauthenticator plugins that support search. To illustrate, we'll create a new\nauthenticator::\n\n >>> @interface.implementer(interfaces.IAuthenticatorPlugin)\n ... class SearchableAuthenticatorPlugin:\n ...\n ... def __init__(self):\n ... self.infos = {}\n ... self.ids = {}\n ...\n ... def principalInfo(self, id):\n ... return self.infos.get(id)\n ...\n ... def authenticateCredentials(self, credentials):\n ... id = self.ids.get(credentials)\n ... if id is not None:\n ... return self.infos[id]\n ...\n ... def add(self, id, title, description, credentials):\n ... self.infos[id] = PrincipalInfo(id, title, description)\n ... self.ids[credentials] = id\n\nThis class is typical of an authenticator plugin. It can both authenticate\nprincipals and find principals given a ID. While there are cases\nwhere an authenticator may opt to not perform one of these two functions, they\nare less typical.\n\nAs with any plugin, we need to register it as a utility::\n\n >>> searchable = SearchableAuthenticatorPlugin()\n >>> provideUtility(searchable, name='Searchable Authentication Plugin')\n\nWe'll now configure the PAU to use only the searchable authenticator::\n\n >>> pau.authenticatorPlugins = ('Searchable Authentication Plugin',)\n\nand add some principals to the authenticator::\n\n >>> searchable.add('bob', 'Bob', 'A nice guy', 'b0b')\n >>> searchable.add('white', 'White Spy', 'Sneaky', 'deathtoblack')\n\nNow when we ask the PAU to find a principal::\n\n >>> pau.getPrincipal('xyz_bob')\n Principal('xyz_bob')\n\nbut only those it knows about::\n\n >>> print(pau.getPrincipal('black'))\n Traceback (most recent call last):\n zope.authentication.interfaces.PrincipalLookupError: black\n\nFound Principal Creates Events\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAs evident in the authenticator's 'createFoundPrincipal' method (see above),\na FoundPrincipalCreatedEvent is published when the authenticator finds a\nprincipal on behalf of PAU's 'getPrincipal'::\n\n >>> clearEvents()\n >>> principal = pau.getPrincipal('xyz_white')\n >>> principal\n Principal('xyz_white')\n\n >>> [event] = getEvents(interfaces.IFoundPrincipalCreated)\n >>> event.principal is principal\n True\n >>> event.info\n PrincipalInfo('white')\n\nThe info has an authenticatorPlugin, but no credentialsPlugin, since none was\nused::\n\n >>> event.info.credentialsPlugin is None\n True\n >>> event.info.authenticatorPlugin is searchable\n True\n\nAs we have seen with authenticated principals, it is common to subscribe to\nprincipal created events to add information to the newly created principal.\nIn this case, we need to subscribe to IFoundPrincipalCreated events::\n\n >>> provideHandler(add_info, [interfaces.IFoundPrincipalCreated])\n\nNow when a principal is created as a result of a search, it's title and\ndescription will be set (by the add_info handler function).\n\nMultiple Authenticator Plugins\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAs with the other operations we've seen, the PAU uses multiple plugins to\nfind a principal. If the first authenticator plugin can't find the requested\nprincipal, the next plugin is used, and so on.\n\nTo illustrate, we'll create and register a second searchable authenticator::\n\n >>> searchable2 = SearchableAuthenticatorPlugin()\n >>> provideUtility(searchable2, name='Searchable Authentication Plugin 2')\n\nand add a principal to it::\n\n >>> searchable.add('black', 'Black Spy', 'Also sneaky', 'deathtowhite')\n\nWhen we configure the PAU to use both searchable authenticators (note the\norder)::\n\n >>> pau.authenticatorPlugins = (\n ... 'Searchable Authentication Plugin 2',\n ... 'Searchable Authentication Plugin')\n\nwe see how the PAU uses both plugins::\n\n >>> pau.getPrincipal('xyz_white')\n Principal('xyz_white')\n\n >>> pau.getPrincipal('xyz_black')\n Principal('xyz_black')\n\nIf more than one plugin know about the same principal ID, the first plugin is\nused and the remaining are not delegated to. To illustrate, we'll add\nanother principal with the same ID as an existing principal::\n\n >>> searchable2.add('white', 'White Rider', '', 'r1der')\n >>> pau.getPrincipal('xyz_white').title\n 'White Rider'\n\nIf we change the order of the plugins::\n\n >>> pau.authenticatorPlugins = (\n ... 'Searchable Authentication Plugin',\n ... 'Searchable Authentication Plugin 2')\n\nwe get a different principal for ID 'white'::\n\n >>> pau.getPrincipal('xyz_white').title\n 'White Spy'\n\n\nIssuing a Challenge\n-------------------\n\nPart of PAU's IAuthentication contract is to challenge the user for\ncredentials when its 'unauthorized' method is called. The need for this\nfunctionality is driven by the following use case:\n\n - A user attempts to perform an operation he is not authorized to perform.\n\n - A handler responds to the unauthorized error by calling IAuthentication\n 'unauthorized'.\n\n - The authentication component (in our case, a PAU) issues a challenge to\n the user to collect new credentials (typically in the form of logging in\n as a new user).\n\nThe PAU handles the credentials challenge by delegating to its credentials\nplugins.\n\nCurrently, the PAU is configured with the credentials plugins that don't\nperform any action when asked to challenge (see above the 'challenge' methods).\n\nTo illustrate challenges, we'll subclass an existing credentials plugin and\ndo something in its 'challenge'::\n\n >>> class LoginFormCredentialsPlugin(FormCredentialsPlugin):\n ...\n ... def __init__(self, loginForm):\n ... self.loginForm = loginForm\n ...\n ... def challenge(self, request):\n ... request.response.redirect(self.loginForm)\n ... return True\n\nThis plugin handles a challenge by redirecting the response to a login form.\nIt returns True to signal to the PAU that it handled the challenge.\n\nWe will now create and register a couple of these plugins::\n\n >>> provideUtility(LoginFormCredentialsPlugin('simplelogin.html'),\n ... name='Simple Login Form Plugin')\n\n >>> provideUtility(LoginFormCredentialsPlugin('advancedlogin.html'),\n ... name='Advanced Login Form Plugin')\n\nand configure the PAU to use them::\n\n >>> pau.credentialsPlugins = (\n ... 'Simple Login Form Plugin',\n ... 'Advanced Login Form Plugin')\n\nNow when we call 'unauthorized' on the PAU::\n\n >>> request = TestRequest()\n >>> pau.unauthorized(id=None, request=request)\n\nwe see that the user is redirected to the simple login form::\n\n >>> request.response.getStatus()\n 302\n >>> request.response.getHeader('location')\n 'simplelogin.html'\n\nWe can change the challenge policy by reordering the plugins::\n\n >>> pau.credentialsPlugins = (\n ... 'Advanced Login Form Plugin',\n ... 'Simple Login Form Plugin')\n\nNow when we call 'unauthorized'::\n\n >>> request = TestRequest()\n >>> pau.unauthorized(id=None, request=request)\n\nthe advanced plugin is used because it's first::\n\n >>> request.response.getStatus()\n 302\n >>> request.response.getHeader('location')\n 'advancedlogin.html'\n\nChallenge Protocols\n~~~~~~~~~~~~~~~~~~~\n\nSometimes, we want multiple challengers to work together. For example, the\nHTTP specification allows multiple challenges to be issued in a response. A\nchallenge plugin can provide a `challengeProtocol` attribute that effectively\ngroups related plugins together for challenging. If a plugin returns `True`\nfrom its challenge and provides a non-None challengeProtocol, subsequent\nplugins in the credentialsPlugins list that have the same challenge protocol\nwill also be used to challenge.\n\nWithout a challengeProtocol, only the first plugin to succeed in a challenge\nwill be used.\n\nLet's look at an example. We'll define a new plugin that specifies an\n'X-Challenge' protocol::\n\n >>> class XChallengeCredentialsPlugin(FormCredentialsPlugin):\n ...\n ... challengeProtocol = 'X-Challenge'\n ...\n ... def __init__(self, challengeValue):\n ... self.challengeValue = challengeValue\n ...\n ... def challenge(self, request):\n ... value = self.challengeValue\n ... existing = request.response.getHeader('X-Challenge', '')\n ... if existing:\n ... value += ' ' + existing\n ... request.response.setHeader('X-Challenge', value)\n ... return True\n\nand register a couple instances as utilities::\n\n >>> provideUtility(XChallengeCredentialsPlugin('basic'),\n ... name='Basic X-Challenge Plugin')\n\n >>> provideUtility(XChallengeCredentialsPlugin('advanced'),\n ... name='Advanced X-Challenge Plugin')\n\nWhen we use both plugins with the PAU::\n\n >>> pau.credentialsPlugins = (\n ... 'Basic X-Challenge Plugin',\n ... 'Advanced X-Challenge Plugin')\n\nand call 'unauthorized'::\n\n >>> request = TestRequest()\n >>> pau.unauthorized(None, request)\n\nwe see that both plugins participate in the challange, rather than just the\nfirst plugin::\n\n >>> request.response.getHeader('X-Challenge')\n 'advanced basic'\n\n\nPluggable-Authentication Prefixes\n---------------------------------\n\nPrincipal ids are required to be unique system wide. Plugins will often provide\noptions for providing id prefixes, so that different sets of plugins provide\nunique ids within a PAU. If there are multiple pluggable-authentication\nutilities in a system, it's a good idea to give each PAU a unique prefix, so\nthat principal ids from different PAUs don't conflict. We can provide a prefix\nwhen a PAU is created::\n\n >>> pau = authentication.PluggableAuthentication('mypau_')\n >>> pau.credentialsPlugins = ('My Credentials Plugin', )\n >>> pau.authenticatorPlugins = ('My Authenticator Plugin', )\n\nWhen we create a request and try to authenticate::\n\n >>> pau.authenticate(TestRequest(credentials='secretcode'))\n Principal('mypau_bob')\n\nNote that now, our principal's id has the pluggable-authentication\nutility prefix.\n\nWe can still lookup a principal, as long as we supply the prefix::\n\n >> pau.getPrincipal('mypas_42')\n Principal('mypas_42', \"{'domain': 42}\")\n\n >> pau.getPrincipal('mypas_41')\n OddPrincipal('mypas_41', \"{'int': 41}\")\n\n\nSearching\n---------\n\nPAU implements ISourceQueriables::\n\n >>> from zope.schema.interfaces import ISourceQueriables\n >>> ISourceQueriables.providedBy(pau)\n True\n\nThis means a PAU can be used in a principal source vocabulary (Zope provides a\nsophisticated searching UI for principal sources).\n\nAs we've seen, a PAU uses each of its authenticator plugins to locate a\nprincipal with a given ID. However, plugins may also provide the interface\nIQuerySchemaSearch to indicate they can be used in the PAU's principal search\nscheme.\n\nCurrently, our list of authenticators::\n\n >>> pau.authenticatorPlugins\n ('My Authenticator Plugin',)\n\ndoes not include a queriable authenticator. PAU cannot therefore provide any\nqueriables::\n\n >>> list(pau.getQueriables())\n []\n\nBefore we illustrate how an authenticator is used by the PAU to search for\nprincipals, we need to setup an adapter used by PAU::\n\n >>> import zope.app.authentication.authentication\n >>> provideAdapter(\n ... authentication.authentication.QuerySchemaSearchAdapter,\n ... provides=interfaces.IQueriableAuthenticator)\n\nThis adapter delegates search responsibility to an authenticator, but prepends\nthe PAU prefix to any principal IDs returned in a search.\n\nNext, we'll create a plugin that provides a search interface::\n\n >>> @interface.implementer(interfaces.IQuerySchemaSearch)\n ... class QueriableAuthenticatorPlugin(MyAuthenticatorPlugin):\n ...\n ... schema = None\n ...\n ... def search(self, query, start=None, batch_size=None):\n ... yield 'foo'\n ...\n\nand install it as a plugin::\n\n >>> plugin = QueriableAuthenticatorPlugin()\n >>> provideUtility(plugin,\n ... provides=interfaces.IAuthenticatorPlugin,\n ... name='Queriable')\n >>> pau.authenticatorPlugins += ('Queriable',)\n\nNow, the PAU provides a single queriable::\n\n >>> list(pau.getQueriables()) # doctest: +ELLIPSIS\n [('Queriable', ...QuerySchemaSearchAdapter object...)]\n\nWe can use this queriable to search for our principal::\n\n >>> queriable = list(pau.getQueriables())[0][1]\n >>> list(queriable.search('not-used'))\n ['mypau_foo']\n\nNote that the resulting principal ID includes the PAU prefix. Were we to search\nthe plugin directly::\n\n >>> list(plugin.search('not-used'))\n ['foo']\n\nThe result does not include the PAU prefix. The prepending of the prefix is\nhandled by the PluggableAuthenticationQueriable.\n\n\nQueryiable plugins can provide the ILocation interface. In this case the\nQuerySchemaSearchAdapter's __parent__ is the same as the __parent__ of the\nplugin::\n\n >>> import zope.location.interfaces\n >>> @interface.implementer(zope.location.interfaces.ILocation)\n ... class LocatedQueriableAuthenticatorPlugin(QueriableAuthenticatorPlugin):\n ...\n ... __parent__ = __name__ = None\n ...\n >>> import zope.component.hooks\n >>> site = zope.component.hooks.getSite()\n >>> plugin = LocatedQueriableAuthenticatorPlugin()\n >>> plugin.__parent__ = site\n >>> plugin.__name__ = 'localname'\n >>> provideUtility(plugin,\n ... provides=interfaces.IAuthenticatorPlugin,\n ... name='location-queriable')\n >>> pau.authenticatorPlugins = ('location-queriable',)\n\nWe have one queriable again::\n\n >>> queriables = list(pau.getQueriables())\n >>> queriables # doctest: +ELLIPSIS\n [('location-queriable', ...QuerySchemaSearchAdapter object...)]\n\nThe queriable's __parent__ is the site as set above::\n\n >>> queriable = queriables[0][1]\n >>> queriable.__parent__ is site\n True\n\nIf the queriable provides ILocation but is not actually locatable (i.e. the\nparent is None) the pau itself becomes the parent::\n\n\n >>> plugin = LocatedQueriableAuthenticatorPlugin()\n >>> provideUtility(plugin,\n ... provides=interfaces.IAuthenticatorPlugin,\n ... name='location-queriable-wo-parent')\n >>> pau.authenticatorPlugins = ('location-queriable-wo-parent',)\n\nWe have one queriable again::\n\n >>> queriables = list(pau.getQueriables())\n >>> queriables # doctest: +ELLIPSIS\n [('location-queriable-wo-parent', ...QuerySchemaSearchAdapter object...)]\n\nAnd the parent is the pau::\n\n >>> queriable = queriables[0][1]\n >>> queriable.__parent__ # doctest: +ELLIPSIS\n <zope.pluggableauth.authentication.PluggableAuthentication object ...>\n >>> queriable.__parent__ is pau\n True\n\n\n================\nPrincipal Folder\n================\n\nPrincipal folders contain principal-information objects that contain principal\ninformation. We create an internal principal using the `InternalPrincipal`\nclass:\n\n >>> from zope.app.authentication.principalfolder import InternalPrincipal\n >>> p1 = InternalPrincipal('login1', '123', \"Principal 1\",\n ... passwordManagerName=\"SHA1\")\n >>> p2 = InternalPrincipal('login2', '456', \"The Other One\")\n\nand add them to a principal folder:\n\n >>> from zope.app.authentication.principalfolder import PrincipalFolder\n >>> principals = PrincipalFolder('principal.')\n >>> principals['p1'] = p1\n >>> principals['p2'] = p2\n\nAuthentication\n--------------\n\nPrincipal folders provide the `IAuthenticatorPlugin` interface. When we\nprovide suitable credentials:\n\n >>> from pprint import pprint\n >>> principals.authenticateCredentials({'login': 'login1', 'password': '123'})\n PrincipalInfo(u'principal.p1')\n\nWe get back a principal id and supplementary information, including the\nprincipal title and description. Note that the principal id is a concatenation\nof the principal-folder prefix and the name of the principal-information object\nwithin the folder.\n\nNone is returned if the credentials are invalid:\n\n >>> principals.authenticateCredentials({'login': 'login1',\n ... 'password': '1234'})\n >>> principals.authenticateCredentials(42)\n\nSearch\n------\n\nPrincipal folders also provide the IQuerySchemaSearch interface. This\nsupports both finding principal information based on their ids:\n\n >>> principals.principalInfo('principal.p1')\n PrincipalInfo('principal.p1')\n\n >>> principals.principalInfo('p1')\n\nand searching for principals based on a search string:\n\n >>> list(principals.search({'search': 'other'}))\n [u'principal.p2']\n\n >>> list(principals.search({'search': 'OTHER'}))\n [u'principal.p2']\n\n >>> list(principals.search({'search': ''}))\n [u'principal.p1', u'principal.p2']\n\n >>> list(principals.search({'search': 'eek'}))\n []\n\n >>> list(principals.search({}))\n []\n\nIf there are a large number of matches:\n\n >>> for i in range(20):\n ... i = str(i)\n ... p = InternalPrincipal('l'+i, i, \"Dude \"+i)\n ... principals[i] = p\n\n >>> pprint(list(principals.search({'search': 'D'})))\n [u'principal.0',\n u'principal.1',\n u'principal.10',\n u'principal.11',\n u'principal.12',\n u'principal.13',\n u'principal.14',\n u'principal.15',\n u'principal.16',\n u'principal.17',\n u'principal.18',\n u'principal.19',\n u'principal.2',\n u'principal.3',\n u'principal.4',\n u'principal.5',\n u'principal.6',\n u'principal.7',\n u'principal.8',\n u'principal.9']\n\nWe can use batching parameters to specify a subset of results:\n\n >>> pprint(list(principals.search({'search': 'D'}, start=17)))\n [u'principal.7', u'principal.8', u'principal.9']\n\n >>> pprint(list(principals.search({'search': 'D'}, batch_size=5)))\n [u'principal.0',\n u'principal.1',\n u'principal.10',\n u'principal.11',\n u'principal.12']\n\n >>> pprint(list(principals.search({'search': 'D'}, start=5, batch_size=5)))\n [u'principal.13',\n u'principal.14',\n u'principal.15',\n u'principal.16',\n u'principal.17']\n\nThere is an additional method that allows requesting the principal id\nassociated with a login id. The method raises KeyError when there is\nno associated principal::\n\n >>> principals.getIdByLogin(\"not-there\")\n Traceback (most recent call last):\n KeyError: 'not-there'\n\nIf there is a matching principal, the id is returned::\n\n >>> principals.getIdByLogin(\"login1\")\n u'principal.p1'\n\nChanging credentials\n--------------------\n\nCredentials can be changed by modifying principal-information objects:\n\n >>> p1.login = 'bob'\n >>> p1.password = 'eek'\n\n >>> principals.authenticateCredentials({'login': 'bob', 'password': 'eek'})\n PrincipalInfo(u'principal.p1')\n\n >>> principals.authenticateCredentials({'login': 'login1',\n ... 'password': 'eek'})\n\n >>> principals.authenticateCredentials({'login': 'bob',\n ... 'password': '123'})\n\n\nIt is an error to try to pick a login name that is already taken:\n\n >>> p1.login = 'login2'\n Traceback (most recent call last):\n ...\n ValueError: Principal Login already taken!\n\nIf such an attempt is made, the data are unchanged:\n\n >>> principals.authenticateCredentials({'login': 'bob', 'password': 'eek'})\n PrincipalInfo(u'principal.p1')\n\nRemoving principals\n-------------------\n\nOf course, if a principal is removed, we can no-longer authenticate it:\n\n >>> del principals['p1']\n >>> principals.authenticateCredentials({'login': 'bob',\n ... 'password': 'eek'})\n\n\n============\nVocabularies\n============\n\nThe vocabulary module provides vocabularies for the authenticator plugins and\nthe credentials plugins.\n\nThe options should include the unique names of all of the plugins that provide\nthe appropriate interface (interfaces.ICredentialsPlugin or\ninterfaces.IAuthentiatorPlugin, respectively) for the current context-- which\nis expected to be a pluggable authentication utility, hereafter referred to as\na PAU.\n\nThese names may be for objects contained within the PAU (\"contained\nplugins\"), or may be utilities registered for the specified interface,\nfound in the context of the PAU (\"utility plugins\"). Contained\nplugins mask utility plugins of the same name. They also may be names\ncurrently selected in the PAU that do not actually have a\ncorresponding plugin at this time.\n\nHere is a short example of how the vocabulary should work. Let's say we're\nworking with authentication plugins. We'll create some faux\nauthentication plugins, and register some of them as utilities and put\nothers in a faux PAU.\n\n >>> from zope.app.authentication import interfaces\n >>> from zope import interface, component\n >>> @interface.implementer(interfaces.IAuthenticatorPlugin)\n ... class DemoPlugin(object):\n ...\n ... def __init__(self, name):\n ... self.name = name\n ...\n >>> utility_plugins = dict(\n ... (i, DemoPlugin(u'Plugin %d' % i)) for i in range(4))\n >>> contained_plugins = dict(\n ... (i, DemoPlugin(u'Plugin %d' % i)) for i in range(1, 5))\n >>> sorted(utility_plugins.keys())\n [0, 1, 2, 3]\n >>> for p in utility_plugins.values():\n ... component.provideUtility(p, name=p.name)\n ...\n >>> sorted(contained_plugins.keys()) # 1 will mask utility plugin 1\n [1, 2, 3, 4]\n >>> @interface.implementer(interfaces.IPluggableAuthentication)\n ... class DemoAuth(dict):\n ...\n ... def __init__(self, *args, **kwargs):\n ... super(DemoAuth, self).__init__(*args, **kwargs)\n ... self.authenticatorPlugins = (u'Plugin 3', u'Plugin X')\n ... self.credentialsPlugins = (u'Plugin 4', u'Plugin X')\n ...\n >>> auth = DemoAuth((p.name, p) for p in contained_plugins.values())\n\n >>> @component.adapter(interface.Interface)\n ... @interface.implementer(component.IComponentLookup)\n ... def getSiteManager(context):\n ... return component.getGlobalSiteManager()\n ...\n >>> component.provideAdapter(getSiteManager)\n\nWe are now ready to create a vocabulary that we can use. The context is\nour faux authentication utility, `auth`.\n\n >>> from zope.app.authentication import vocabulary\n >>> vocab = vocabulary.authenticatorPlugins(auth)\n\nIterating over the vocabulary results in all of the terms, in a relatively\narbitrary order of their names. (This vocabulary should typically use a\nwidget that sorts values on the basis of localized collation order of the\nterm titles.)\n\n >>> [term.value for term in vocab] # doctest: +NORMALIZE_WHITESPACE\n [u'Plugin 0', u'Plugin 1', u'Plugin 2', u'Plugin 3', u'Plugin 4',\n u'Plugin X']\n\nSimilarly, we can use `in` to test for the presence of values in the\nvocabulary.\n\n >>> ['Plugin %s' % i in vocab for i in range(-1, 6)]\n [False, True, True, True, True, True, False]\n >>> 'Plugin X' in vocab\n True\n\nThe length reports the expected value.\n\n >>> len(vocab)\n 6\n\nOne can get a term for a given value using `getTerm()`; its token, in\nturn, should also return the same effective term from `getTermByToken`.\n\n >>> values = ['Plugin 0', 'Plugin 1', 'Plugin 2', 'Plugin 3', 'Plugin 4',\n ... 'Plugin X']\n >>> for val in values:\n ... term = vocab.getTerm(val)\n ... assert term.value == val\n ... term2 = vocab.getTermByToken(term.token)\n ... assert term2.token == term.token\n ... assert term2.value == val\n ...\n\nThe terms have titles, which are message ids that show the plugin title or id\nand whether the plugin is a utility or just contained in the auth utility.\nWe'll give one of the plugins a dublin core title just to show the\nfunctionality.\n\n >>> import zope.dublincore.interfaces\n >>> class ISpecial(interface.Interface):\n ... pass\n ...\n >>> interface.directlyProvides(contained_plugins[1], ISpecial)\n >>> @interface.implementer(zope.dublincore.interfaces.IDCDescriptiveProperties)\n ... @component.adapter(ISpecial)\n ... class DemoDCAdapter(object):\n ... def __init__(self, context):\n ... pass\n ... title = u'Special Title'\n ...\n >>> component.provideAdapter(DemoDCAdapter)\n\nWe need to regenerate the vocabulary, since it calculates all of its data at\nonce.\n\n >>> vocab = vocabulary.authenticatorPlugins(auth)\n\nNow we'll check the titles. We'll have to translate them to see what we\nexpect.\n\n >>> from zope import i18n\n >>> import pprint\n >>> pprint.pprint([i18n.translate(term.title) for term in vocab])\n [u'Plugin 0 (a utility)',\n u'Special Title (in contents)',\n u'Plugin 2 (in contents)',\n u'Plugin 3 (in contents)',\n u'Plugin 4 (in contents)',\n u'Plugin X (not found; deselecting will remove)']\n\ncredentialsPlugins\n------------------\n\nFor completeness, we'll do the same review of the credentialsPlugins.\n\n >>> @interface.implementer(interfaces.ICredentialsPlugin)\n ... class DemoPlugin(object):\n ...\n ... def __init__(self, name):\n ... self.name = name\n ...\n >>> utility_plugins = dict(\n ... (i, DemoPlugin(u'Plugin %d' % i)) for i in range(4))\n >>> contained_plugins = dict(\n ... (i, DemoPlugin(u'Plugin %d' % i)) for i in range(1, 5))\n >>> for p in utility_plugins.values():\n ... component.provideUtility(p, name=p.name)\n ...\n >>> auth = DemoAuth((p.name, p) for p in contained_plugins.values())\n >>> vocab = vocabulary.credentialsPlugins(auth)\n\nIterating over the vocabulary results in all of the terms, in a relatively\narbitrary order of their names. (This vocabulary should typically use a\nwidget that sorts values on the basis of localized collation order of the term\ntitles.) Similarly, we can use `in` to test for the presence of values in the\nvocabulary. The length reports the expected value.\n\n >>> [term.value for term in vocab] # doctest: +NORMALIZE_WHITESPACE\n [u'Plugin 0', u'Plugin 1', u'Plugin 2', u'Plugin 3', u'Plugin 4',\n u'Plugin X']\n >>> ['Plugin %s' % i in vocab for i in range(-1, 6)]\n [False, True, True, True, True, True, False]\n >>> 'Plugin X' in vocab\n True\n >>> len(vocab)\n 6\n\nOne can get a term for a given value using `getTerm()`; its token, in\nturn, should also return the same effective term from `getTermByToken`.\n\n >>> values = ['Plugin 0', 'Plugin 1', 'Plugin 2', 'Plugin 3', 'Plugin 4',\n ... 'Plugin X']\n >>> for val in values:\n ... term = vocab.getTerm(val)\n ... assert term.value == val\n ... term2 = vocab.getTermByToken(term.token)\n ... assert term2.token == term.token\n ... assert term2.value == val\n ...\n\nThe terms have titles, which are message ids that show the plugin title or id\nand whether the plugin is a utility or just contained in the auth utility.\nWe'll give one of the plugins a dublin core title just to show the\nfunctionality. We need to regenerate the vocabulary, since it calculates all\nof its data at once. Then we'll check the titles. We'll have to translate\nthem to see what we expect.\n\n >>> interface.directlyProvides(contained_plugins[1], ISpecial)\n >>> vocab = vocabulary.credentialsPlugins(auth)\n >>> pprint.pprint([i18n.translate(term.title) for term in vocab])\n [u'Plugin 0 (a utility)',\n u'Special Title (in contents)',\n u'Plugin 2 (in contents)',\n u'Plugin 3 (in contents)',\n u'Plugin 4 (in contents)',\n u'Plugin X (not found; deselecting will remove)']\n\n\n=======\nChanges\n=======\n\n6.0 (2025-09-12)\n----------------\n\n* Replace ``pkg_resources`` namespace with PEP 420 native namespace.\n\n* Drop support for Python 3.8.\n\n\n5.1 (2024-11-29)\n----------------\n\n- Add support for Python 3.12, 3.13.\n\n- Drop support for Python 3.7.\n\n- Fix tests to support multipart 1.x+ versions.\n\n\n5.0 (2023-02-09)\n----------------\n\n- Drop support for Python 2.7, 3.3, 3.4, 3.5, 3.6.\n\n- Add support for Python 3.7, 3.8, 3.9, 3.10, 3.11.\n\n\n4.0.0 (2017-05-02)\n------------------\n\n- Drop test dependency on zope.app.zcmlfiles and zope.app.testing.\n\n- Drop explicit dependency on ZODB3.\n\n- Add support for Python 3.4, 3.5 and 3.6, and PyPy.\n\n\n3.9 (2010-10-18)\n----------------\n\n* Move concrete IAuthenticatorPlugin implementations to\n zope.pluggableauth.plugins. Leave backwards compatibility imports.\n\n* Use zope.formlib throughout to lift the dependency on zope.app.form. As it\n turns out, zope.app.form is still a indirect test dependency though.\n\n3.8.0 (2010-09-25)\n------------------\n\n* Using python's ``doctest`` module instead of deprecated\n ``zope.testing.doctest[unit]``.\n\n* Moved the following views from `zope.app.securitypolicy` here, to inverse\n dependency between these two packages, as `zope.app.securitypolicy`\n deprecated in ZTK 1.0:\n\n - ``@@grant.html``\n - ``@@AllRolePermissions.html``\n - ``@@RolePermissions.html``\n - ``@@RolesWithPermission.html``\n\n3.7.1 (2010-02-11)\n------------------\n\n* Using the new `principalfactories.zcml` file, from ``zope.pluggableauth``,\n to avoid duplication errors, in the adapters registration.\n\n3.7.0 (2010-02-08)\n------------------\n\n* The Pluggable Authentication utility has been severed and released\n in a standalone package: `zope.pluggableauth`. We are now using this\n new package, providing backward compatibility imports to assure a\n smooth transition.\n\n3.6.2 (2010-01-05)\n------------------\n\n* Fix tests by using zope.login, and require new zope.publisher 3.12.\n\n3.6.1 (2009-10-07)\n------------------\n\n* Fix ftesting.zcml due to ``zope.securitypolicy`` update.\n\n* Don't use ``zope.app.testing.ztapi`` in tests, use zope.component's\n testing functions instead.\n\n* Fix functional tests and stop using port 8081. Redirecting to\n different port without trusted flag is not allowed.\n\n3.6.0 (2009-03-14)\n------------------\n\n* Separate the presentation template and camefrom/redirection logic for the\n ``loginForm.html`` view. Now the logic is contained in the\n ``zope.app.authentication.browser.loginform.LoginForm`` class.\n\n* Fix login form redirection failure in some cases with Python 2.6.\n\n* Use the new ``zope.authentication`` package instead of ``zope.app.security``.\n\n* The \"Password Manager Names\" vocabulary and simple password manager registry\n were moved to the ``zope.password`` package.\n\n* Remove deprecated code.\n\n3.5.0 (2009-03-06)\n------------------\n\n* Split password manager functionality off to the new ``zope.password``\n package. Backward-compatibility imports are left in place.\n\n* Use ``zope.site`` instead of ``zope.app.component``. (Browser code still\n needs ``zope.app.component`` as it depends on view classes of this\n package.)\n\n3.5.0a2 (2009-02-01)\n--------------------\n\n* Make old encoded passwords really work.\n\n3.5.0a1 (2009-01-31)\n--------------------\n\n* Use ``zope.container`` instead of ``zope.app.container``. (Browser code\n still needs ``zope.app.container`` as it depends on view classes of this\n package.)\n\n* Encoded passwords are now stored with a prefix ({MD5}, {SHA1},\n {SSHA}) indicating the used encoding schema. Old (encoded) passwords\n can still be used.\n\n* Add an SSHA password manager that is compatible with standard LDAP\n passwords. As this encoding gives better security agains dictionary\n attacks, users are encouraged to switch to this new password schema.\n\n* InternalPrincipal now uses SSHA password manager by default.\n\n3.4.4 (2008-12-12)\n------------------\n\n* Depend on zope.session instead of zope.app.session. The first one\n currently has all functionality we need.\n* Fix deprecation warnings for ``md5`` and ``sha`` on Python 2.6.\n\n3.4.3 (2008-08-07)\n------------------\n\n* No changes. Retag for correct release on PyPI.\n\n3.4.2 (2008-07-09)\n-------------------\n\n* Make it compatible with zope.app.container 3.6.1 and 3.5.4 changes,\n Changed ``super(BTreeContainer, self).__init__()`` to\n ``super(GroupFolder, self).__init__()`` in ``GroupFolder`` class.\n\n3.4.1 (2007-10-24)\n------------------\n\n* Avoid deprecation warning.\n\n3.4.0 (2007-10-11)\n------------------\n\n* Updated package meta-data.\n\n3.4.0b1 (2007-09-27)\n--------------------\n\n* First release independent of Zope.\n",
"bugtrack_url": null,
"license": "ZPL-2.1",
"summary": "Principals and groups management for the pluggable authentication utility",
"version": "6.0",
"project_urls": {
"Homepage": "http://github.com/zopefoundation/zope.app.authentication"
},
"split_keywords": [
"zope3",
"authentication",
"pluggable",
"principal",
"group"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "3d048f50635710f827864dd760bc93f30503c56afd399835c724dae5fe0adf45",
"md5": "d835e9c9c1441c57de6db1cd44bbe8a4",
"sha256": "d339967960bbed59d7bd1a8c9ce6f3f0fd4d89818b099afe9d562da42b2d46da"
},
"downloads": -1,
"filename": "zope_app_authentication-6.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "d835e9c9c1441c57de6db1cd44bbe8a4",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.9",
"size": 87883,
"upload_time": "2025-09-12T06:39:55",
"upload_time_iso_8601": "2025-09-12T06:39:55.990678Z",
"url": "https://files.pythonhosted.org/packages/3d/04/8f50635710f827864dd760bc93f30503c56afd399835c724dae5fe0adf45/zope_app_authentication-6.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "8107f7b02a13eda3775d7e63ecd33fe7b1138b9dcdfff69998e0c9c7a2925958",
"md5": "58a64ac3b14867e3988632001505545f",
"sha256": "52bda41e8b759f27283be4aaf6ec44147f4d44a5f2f185b4389901634b81d688"
},
"downloads": -1,
"filename": "zope_app_authentication-6.0.tar.gz",
"has_sig": false,
"md5_digest": "58a64ac3b14867e3988632001505545f",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.9",
"size": 77530,
"upload_time": "2025-09-12T06:39:57",
"upload_time_iso_8601": "2025-09-12T06:39:57.621425Z",
"url": "https://files.pythonhosted.org/packages/81/07/f7b02a13eda3775d7e63ecd33fe7b1138b9dcdfff69998e0c9c7a2925958/zope_app_authentication-6.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-09-12 06:39:57",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "zopefoundation",
"github_project": "zope.app.authentication",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"tox": true,
"lcname": "zope.app.authentication"
}