Mixing pyramid authentication policies

I am writing an application that will have some HTML content (mapping tables, etc.) as well as a JSON API.

For regular HTML, I use AuthTktAuthenticationPolicy for authentication and ACLAuthorizationPolicy for authorization. Thus, the user is provided with a login form and upon successful login to the auth_tkt cookie. The system is operating normally.

Now I want to replicate a similar system for the JSON API. The problem is that the user will not have to be logged in for API requests. Therefore, for each request, the api_key parameter is api_key . Based on the key, if I find a valid user, I will send back JSON. Otherwsie I am showing page 403.

One way to do it in every view

 api_key = request.GET.get('api_key',None) user = FrontEndUsers.User_by_api_key(api_key) if user: #Process view else: return HTTPForbidden 

However, there seems to be too much boiler plate to use for each point of view to make exaccty an authentication policy would do. Can I specify a separate authentication policy for JSON routes? Or is there any other way to do this?

EDIT

Secondly, it seems that even with AuthTktAuthenticationPolicy I need to do security.authenticated_userid() in all views (if I need authentication information). I already considered this in a separate function

 def get_auth_info(): user_id = security.authenticated_userid() login_info = {} if user_id is not None: login_info['login'] = True login_info['logged_in_user'] = FrontendUsers.get_user_by_id(user_id).name else: login_info['login'] = False return login_info 

I can enable the API_key check function call in this function so that none of my views change (I still only call get_auth_info() ), and yet I can check if the correct API key was presented.

I would still like to see if there are other ways to do this or if there is a problem with my current circuit

+4
source share
1 answer

Have you ever mentioned how you use permissions? The proper use of permissions and ACLs in your views should prevent you from executing this template at the beginning of your function. For the simple paste you showed, you just need permission='logged_in' and ACE mapping (Allow, Authenticated, 'logged_in') , but of course you can become more complex if necessary.

It is not possible to specify different authentication policies for different views in a simple way, because the authentication policies in the pyramid must be global. You can do this globally through pyramid_multiauth. Or you can write your own policy that wraps several policies and sends one or the other, depending on the properties of the request.

+2
source

Source: https://habr.com/ru/post/1489458/


All Articles