simple Authentication and ACL using cornice

861 Views Asked by At

I have a RESTful API written in pyramid/cornice. It provides an API for an Ember client.

I have followed the cornice tutorial and have a valid_token validator which I use on many views as methods of resource classes.

def valid_token(request):
    header = 'Authorization'
    token = request.headers.get(header)
    if token is None:
        request.errors.add('headers', header, "Missing token")
        request.errors.status = 401
        return
    session = DBSession.query(Session).get(token)
    if not session:
        request.errors.add('headers', header, "invalid token")
        request.errors.status = 401
    request.validated['session'] = session

Now I want to start selectively protecting resources. The Pyramid way seems to be to register authentication/authorization policies. The ACLAuthorizationPolicy seems to provide access to the nice ACL tooling in pyramid. However, it seems that pyramid needs both authentication and authorization policies to function. Since I'm authenticating with my validator this is confusing me.

Can I use ACL to control authorization whilst authenticating using my cornice valid_token validator? Do I need to register pyramid authentication or authorization policies?

I'm a bit confused, having little experience of using ACL in pyramid.

2

There are 2 best solutions below

2
On BEST ANSWER

It is not an easy question :)

Shortly:

  • What you implemented in your validator is already taken care of by Pyramid with an AuthenticationPolicy
  • Start setting up a SessionAuthenticationPolicy with your custom callback (see code)
  • Once this authn setup, you will have those 401 responses, and your session value in the request.authenticated_userid attribute. You can also custom stuff in the request.registry object.

The only reason to keep your validator is if you want to return the invalid token messages in the 401 response. But for that, you can define a custom 401 pyramid view (using @forbidden_view_config)

Once you have that, you can setup a custom authorization for your views. You can find a very simple example in Cliquet first versions here : authz code and view perm

Good luck!

0
On

You may wanna do something like:

from pyramid.authentication import SessionAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from your_module import valid_token 

authn_policy = SessionAuthenticationPolicy(debug=True, callback=valid_token)
authz_policy = ACLAuthorizationPolicy()

config = Configurator(authentication_policy=authn_policy,authorization_policy=authz_policy)

And ofcourse in the Configuration will receive other arguments like settigns, locale_negociator, ...........

Hope this will help