mardi 27 octobre 2015

How can I disable Authorization header cache in Ruby On Rails API?

I have developed a stateless RESTful API in Ruby On Rails. The way it works is that when you log in you receive a token, that you then use as an Authorization header to make requests.

There are two different roles available in the API: an Admin role and a Client role.

What I have done is add some role constraints to the routes so I can have the same endpoint pointing to different methods in the controller based on the specific role, like so (from config/routes.rb):

get '/courses', to: 'courses#admin_index', constraints: admin_constraints get '/courses', to: 'courses#client_index', constraints: client_constraints.

The constraints are implemented like this:

admin_constraints = RoleRouteConstraint.new(User::ROLES[:admin]) client_constraints = RoleRouteConstraint.new(User::ROLES[:client])

Where the RoleRouteConstraint retrieves the user that the Authorization header token belongs to, checks it's role and returns true if the role matches the constructor parameter.

The problem is that when I switch roles, Rails somehow caches my Authorization header from the previous role. Meaning that after I log in in the admin panel (as an admin), interact with the interface, and then go into the client interface, perform some actions, the API will keep my role as a client. If I then try to perform admin-specific actions, like so:

put '/courses/:id', to: 'courses#update', constraints: admin_constraints

I will not be able, since the API thinks I'm still logged in as a client. The thing is that it will work if I restart my rails server. Locally I'm using POW and in staging/production I'm using apache2. So if I perform a Rails restart and repeat the request as an admin, then it will work.

Anyone have any ideas please?

Aucun commentaire:

Enregistrer un commentaire