Search code examples
phpauthenticationmodel-view-controlleraclrbac

PHP - Where to put RBAC and Authentification in an MVC application?


I'm working on an MVC application with this structure:

   Request
      V
FrontController <-> Router
      V
  Controller <-> Model
      V
     View

I have two other components that I need to place in this structure:

  • Authentification: Logs the user in using the $_SESSION global variable;
  • RBAC: Role Based Access Control that can check if a role has access granted to a "ressource" (Controller method).

Every users can have any given number of roles (they can also have none).

Now, I need to place those two components in my applications, I need them to be able to:

  • If the User isn't authed and that the Request requires a authed User to be executed, the client should be redirected to a login page;
  • If the RBAC sees that the authed User doesn't have a role that has access granted to the required "ressource" to execute the Controller's method, the Controller's method should still be executed but with knowledge that the User did not have the permission to do so (Example: A User writes an article but doesn't have the right to publish it, so the article is saved as a draft and the User is told that a Moderator will have to publish it).

I already have a few ideas where to locate the Authentification and RBAC but I'm not sure:

  • Authentification could go in the FrontController or the Router;
  • RBAC could go in the FrontController or the Controller.

I saw someone putting the RBAC in the model but I don't understand why.

I'd like to have some insight on the subject please. Where should I put the Authentification and RBAC components?

Thank you!


Solution

  • In a typical MVC application the authentication check (i.e. "if not auth, then stop and render the login page instead") is done very early in processing the request, while the business logic (i.e. "if user has this permission then this happens, otherwise that happens") is handled within the "C" (the controller).

    Most frameworks have a mechanism in place for tests like the authentication check your are describing - names vary but I have often seen it called "middleware".

    The role based access control is purely your implementation.