Where should the authorization logic go in an api based application?

耗尽温柔 提交于 2019-12-11 06:57:57

问题


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.


回答1:


tl;dr

Outside the app - always externalize authorization. Decouple your authorization logic from your business logic.

Longer answer

Since the beginning of SOA (service-oriented architecture), API architectures and now microservices, the trend has been towards breaking down application silos and designing systems in such a way you can reuse common functionality. For instance, you use a central authentication service (you wouldn't, I hope, implement your own authentication scheme) and a central logging mechanism.

The same applies to authorization. There is something called externalized authorization which promotes:

  • decoupling authorization logic from the application. Many dev frameworks already do that (Spring Security, Microsoft Claims, Ruby CanCanCan...)
  • centralizing authorization logic into a single point of management.
  • expressing authorization logic as human-readable policies. This means you can write policies such as
    • Doctors can view the medical records of patients they have a relationship with
  • using attributes to define these policies: this is called attribute-based access control (ABAC). It is the de factor authorization model for new app developments (such as API). NIST published an excellent report on the topic in 2013.

Architecture

ABAC promotes the following architecture and flow (more details here)

  • Policy Enforcement Point
  • Policy Decision Point
  • Policy Information Point
  • Policy Administration Point

ABAC Implementation: XACML & ALFA

Generic approaches

There are 2 standards that implement ABAC today. XACML provides both a language and an architecture (see above). ALFA provides a language.

ABAC in Ruby

Check out this project: CanCanCan.



来源:https://stackoverflow.com/questions/44396691/where-should-the-authorization-logic-go-in-an-api-based-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!