Authentication Keyring Module
Provides facilities for managing different user credentials (Username and API keys, etc.) and can be used as such for automatic user authentication and authorisation. Auth can be extended to support arbitrary token types.
Using auth:
Firstly, import auth package:
>>> import auth
Initialize new keyring by invoking:
>>> my_keys = auth.Keyring()
Different types of authentication “keys” can be added. Scope of the keys may be also defined by setting a domain in which the key is valid.
An example of adding a username token e.g. for HTTPBasic authentication
>>> my_keys.add_token_username('johndoe', 'mypassword', domain='www.example.com')
An example of adding a generic API key:
>>> my_keys.add_token_apikey('A1B2C3D4E5', domain='api.example.com')
Keys with specified criteria can be retrieved by invoking keys() method:
>>> a_key = my_keys.keys()[0]
>>> a_key.username
'johndoe'
>>> a_key.password
'mypassword'
>>> a_key.match_domain('www.example.com')
True
>>> a_key.match_domain('www.example.org')
False
Generic API key token Parameters:
api_key secret (optional) domain (optional)
Keyring is used to manage a set of tokens
Generic method for adding new token to the keyring
Convenience method for adding API key token to the keyring
Convenience method for adding username token to the keyring
Find keys by specified criteria. Finds all by defaul
domain - Return only keys that match the given domain
Merge tokens from file to the keyring
Save keyring to a file
Token
Does this token match a given domain?
Test cases:
Import Token model:
>>> from auth import Token
Create test token:
>>> t = Token(domain='example.com')
Direct match:
>>> t.match_domain('example.com')
True
Doesn’t match:
>>> t.match_domain('example.org')
False
Matches a subdomain:
>>> t.match_domain('api.example.com')
True
Subdomain matches, but domain doesn’t:
>>> t.match_domain('api.example.org')
False
Spoof #1: Domain name in pathname
>>> t.match_domain('api.example.org/example.com')
False
Spoof #2: Domain name as a urlencoded argument
>>> t.match_domain('api.example.org/?url=example.com')
False
Spoof #3: Domain name in subdomain
>>> t.match_domain('example.com.spoof')
False
Token is valid for several domains:
>>> t2 = Token(domain=['example.com', 'example.org'])
Try first:
>>> t2.match_domain('example.com')
True
Try second:
>>> t2.match_domain('example.org')
True
Try something that should not work
>>> t2.match_domain('example.biz')
False
Create token for a specific location within a domain
>>> t3 = Token(domain='example.com/api')
Try matching location:
>>> t3.match_domain('example.com/api/callback')
True
Try invalid location:
>>> t3.match_domain('example.org/api')
False
Create token valid only for a specific port:
>>> t4 = Token('example.com:1234')
>>> t4.match_domain('example.com')
False
>>> t4.match_domain('example.com:1234')
True
Ordinary username + password token Parameters:
username password (optional) domain (optional)