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.
It is not an easy question :)
Shortly:
SessionAuthenticationPolicy
with your custom callback (see code)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!