I'm working on a little MVC framework and I'm wondering what the "best way" is to structure things so secure pages/controllers always ensure the user is logged in (and thus automatically redirects to a login page--or elsewhere--if not). Obviously, there are a lot of ways to do it, but I'm wondering what solution(s) are the most common or are considered the best practice. Some ideas I had:
- Explicitly call
user->isLoggedIn()
at the beginning of your controller action method? (Seems far too easy to forget and leave an important page unsecure on accident) - Make your controller extend a
secureController
that always checks for log开发者_JS百科in in the constructor? - Do this check in the model when secure information is requested? (Seems like redundant calls would be made)
- Something else entirely?
Note: I'm working in PHP, though the question is not language-dependent.
ASP.Net MVC does this nicely with the [Authorize] attribute on the controller class which needs authorization
It isn't the only way to do it, but...
All client requests go to a FilterManager, which builds a FilterChain based on the details of the request. Within the FilterChain, if the resource is one that requires a logged in state, and the client isn't logged in, the request can be redirected. The original request can be saved and redirected to the log in page, allowing continuation from the original request (this is optional).
It's a J2EE design pattern, but you can implement it in any language once you get the idea. In this case, one of the "filters" is an "authentication filter". See http://java.sun.com/blueprints/corej2eepatterns/Patterns/InterceptingFilter.html for details of the idea (in Java).
The advantages of this is that all pages will centralize their logic in the FilterManager, so a page need only have their call to the FilterManager. Additionally, you can add debugging filters / logging filters / etc which can assist in maintaining / developing your code.
精彩评论