Token-based Authentication with Cornice for Pyramid

1k Views Asked by At

I am using the Resources strategy of developing a RESTful API within a Pyramid App. http://cornice.readthedocs.io/en/latest/resources.html. However I couldn't find an example of adding authentication for the API. Any guidance is greatly appreciated.

1

There are 1 best solutions below

1
On

As Antoine Leclair pointed out, Cornice relies on Pyramid. You will have to enable an authorization and an authentication policies during your app initialization. For example (here using pyramid-jwt):

from pyramid.config import Configurator
from pyramid.authorization import ACLAuthorizationPolicy

def main():
    config = Configurator()
    # Pyramid requires an authorization policy to be active.
    config.set_authorization_policy(ACLAuthorizationPolicy())
    # Enable JWT authentication.
    config.include('pyramid_jwt')
    config.set_jwt_authentication_policy('secret')

You can also create your own policy, by inheriting from builtin Pyramid classes in pyramid.authentication:

from pyramid.authentication import CallbackAuthenticationPolicy
from pyramid.interfaces import IAuthenticationPolicy
from zope.interface import implementer

@implementer(IAuthenticationPolicy)
class MyAuthenticationPolicy(CallbackAuthenticationPolicy):
    def __init__(self, realm='Realm'):
        self.realm = realm

    def unauthenticated_userid(self, request):
        user_id = self._get_credentials(request)
        return user_id

    def forget(self, request):
        return [('WWW-Authenticate', 'MyAuth realm="%s"' % self.realm)]

    def _get_credentials(self, request):
        authorization = request.headers.get('Authorization', '')
        # your own strategy...
        # if valid: return user_id
        # else return None

Check out existing projects on awesome-pyramid to see if what you need is already there...