0

I have a brand new Rails api based application, where i need to implement authorization.

Overall Architecture:

React frontend -> Rails API layer -> Rails model/server layer

While exploring different approaches, I have got a confusion.

  1. Should we put the authorization logic in API layer or Service layer?
  2. API Layer Approach: We will build some authorization middleware that will sit between our front end and API layer and all our api calls will be routed thorough the authorization middleware to check if the user is allowed to call that parituclar api.
  3. Service Layer: All the authorization check will go to service layer and we will have check before every db operation if the user is allowed to do so. (Using cancancan / pundit) and if the user is not allowed throw the error message to API layer.

It would be a great help, if someone could suggest based on their experience.

Deepak Kumar Padhy
  • 1,178
  • 2
  • 8
  • 7

1 Answers1

2

Obviously authorization needs to be checked on the server side, as relying solely on client checks opens you up to malicious clients. There's no general consensus on where in the server-side code you should do these checks, but I'm going to argue for it being as close to the edge as possible.

For one, this is often the easiest. You have immediate access to the data of the call, and can return the appropriate error message directly instead of relying on an exception bubbling up through several layers.

Secondly, authorization is often more complex than you might anticipate. Take GitHub for example - to perform certain sensitive actions, you most first re-enter your password. This sort of check tends to be much easier to deal with on a page-by-page basis, rather than building complex conditionals into the model layer.

From a security perspective, there's definitely an argument to be made for a deep authorization approach, namely that you don't rely on developers remembering to handle authorization in every new endpoint. However, my opinion is that the clarity and simplicity gained from an edge-based approach outweigh these benefits.

Xiong Chiamiov
  • 9,384
  • 2
  • 34
  • 76