Search code examples
phprestrbac

PHP / REST - How do I implement a role based access of my API?


I have started a PHP project (A Project Management Item Tracking Tool) using an API centric approach and have made a fairly good start.

I have created 2 GET the methods so far I want to restrict access but don't know where to start.

In the context of my database

  • Project is the container that encapsulates different actionitems.
  • Actionitems are 'assigned' to a user.

  • Users exist in a database.

  • Roles as assigned to a user. (User, Admin, Super)


  • User can only update their own item

  • Admin had create and update privilege

  • Super has total administrative privilege


My question is: Where should I start in PHP to only allow accessing the api via proper users, either via a login api, or some other means? Any help to get started would get me going.

To start I have successfully created an endpoint to access access resource (actionitems) using a JSON string to test the response.

Existing Endpoints I want to restrict

GET /api/actionitems/

With a general structure to access specific resources within a table as follows:

GET /api/actionitems/4

Note additional api endpoints should be accessed as follows

each route as up to 3 route tokens (following the /api/)

GET /api/users/123/actionitems   (get all actionitems for user 123)


GET /api/users/123/actionitems?<more-filers> applies further filtering

Solution

  • You need to handle authentication and authorization for your APIs.

    These are very basic steps to understand the solution:

    • Client calls login API using user credentials(username, password).
    • Server authenticates user credentials and generates a token.
    • Server stores this token in database against authenticated user id and responds to client.
    • Server already has authorization role rights to access different APIs associated with this authenticated user in database.
    • Client calls resource APIs using token provided by login API.
    • Server verify token in database and fetch user and user role rights against this token for authorization.
    • Resource APIs authorize and provides required data or perform actions according to authenticated user role rights.

    There are multiple ways to achieve this in standardize way: