Last active
October 9, 2015 15:57
-
-
Save mmerickel/d663298331594ae954d1 to your computer and use it in GitHub Desktop.
simple token-based authentication policy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pyramid.authorization import ACLAuthorizationPolicy | |
from pyramid.security import ( | |
Authenticated, | |
Everyone, | |
) | |
log = __import__('logging').getLogger(__name__) | |
class OAuthAuthenticationPolicy(object): | |
def unauthenticated_userid(self, request): | |
""" Find the authentication token.""" | |
for identifier in [ | |
self.identify_authorization_header, | |
]: | |
token = identifier(request) | |
if token is not None: | |
return token | |
def identify_authorization_header(self, request): | |
try: | |
auth_hdr = request.authorization | |
except ValueError: | |
log.warn('invalid authorization header format') | |
log.debug( | |
'authorization header="%s"', request.headers['Authorization']) | |
auth_hdr = None | |
if auth_hdr is not None and auth_hdr[0] == 'Bearer': | |
token = auth_hdr[1] | |
log.debug( | |
'detected access token=%s from authorization header', token) | |
return token | |
def authenticated_userid(self, request): | |
# use request.user as the central code for verifying and | |
# loading a token from the database | |
user = request.user | |
if user: | |
return user.id | |
def effective_principals(self, request): | |
principals = [Everyone] | |
if request.user: | |
principals += [Authenticated] | |
user = request.user | |
principals += [ | |
'u:{0}'.format(user.id), | |
] | |
# possibly add some group-based principals here too based | |
# on properties of the user | |
return principals | |
def remember(self, request, userid, **kw): | |
return [] | |
def forget(self, request): | |
return [] | |
def get_user(request): | |
token = request.unauthenticated_userid | |
if token: | |
# inspect the token and cross-ref with your database, | |
# find the user and return it assuming the token is valid | |
user = | |
return user | |
def includeme(config): | |
authn_policy = OAuthAuthenticationPolicy() | |
authz_policy = ACLAuthorizationPolicy() | |
config.set_authentication_policy(authn_policy) | |
config.set_authorization_policy(authz_policy) | |
config.add_request_method(get_user, 'user', reify=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment