RESTFul API endpoint design with filtering and authorization

后端 未结 2 971
灰色年华
灰色年华 2021-01-13 01:29

I am designing a REST API with consumers that have different permissions. I understand that a representation of a resource should not change according to user. Therefore I

相关标签:
2条回答
  • 2021-01-13 02:02

    In this case you can get away with just two endpoints (and one header!). Make sure the API for /documents is returning the Vary: Authorization header. Then you can use

    GET /api/documents              // return all docs the logged-in user can see
    GET /api/documents?userId=bob   // return all of bob's docs that the logged-in user can see
    GET /api/documents/123          // return doc 123 if the logged-in user can see it    
    

    It is not entirely unreasonable to nest the user a la GET /api/users/bob/documents. I find it to be harder for end users to learn APIs with a large number of endpoints, and I feel that the nested approach tends to create many endpoints. It's conceptually easier to go to /documents and see what you can filter on, rather than look at each endpoint and see what filters it has.

    0 讨论(0)
  • 2021-01-13 02:04

    I would keep business logic and authorization logic entirely separate. If you want to retrieve document XYZ, you wouldn't pass the user id as an HTTP parameter.

    You suggested /api/documents?user=12 but in fact it should just be /api/documents. The user information should come from the authentication layer.

    Similarly authorization should be entirely separate. The reasons for that are:

    • separation of concern
    • ability to update authorization logic independently of of business logic
    • avoid impact on API design

    The API should only reflect those business objects you care about e.g. documents in this case (possibly also users should you wish to display a user profile...).

    To handle authentication, use the container's standard techniques (e.g. HTTP Basic authentication) or use advanced authentication techniques (OAuth..) via a dedicated framework.

    To handle authorization, use a filter, an interceptor. In the Java world (where JAX-RS implements REST), have a look at the Jersey interceptors and filters. You then want the interceptor (or policy enforcement point - PEP) to query an external authorization service (or policy decision point).

    Protecting a REST API - Architecture

    Have a further look at ABAC, the attribute-based access control model, and XACML, the eXtensible Access Control Markup Language which explain how to control access to your REST APIs without mixing business logic and authorization logic.

    0 讨论(0)
提交回复
热议问题