Java Spring – Should Login Logic Be in Controller or Service in MVC Webapp?

javaspring

I'm using Shiro as my security manager for a Spring MVC web application.

The login basically happens in these lines:

Subject user = SecurityUtils.getSubject();
user.login(new UsernamePasswordToken(username, password));

Where should I put this logic? login() can throw exceptions if the requested user doesn't exist or wrong password was provided, etc. Should I call the code from my controller and do the error handling there or should I call it from my service layer, catch exceptions and rethrow my own up to the controller?

Best Answer

Either of the two options you present is valid.

Services (the Model layer) are allowed to call other services. So having your service call the authentication service is acceptable.

Likewise, Controllers are allowed to call to services so that option is equally acceptable.

If Shiro is providing your only authentication mechanisms, then it's kind of a toss-up between either approach. Calling from the Controller would seem a little faster to develop and potentially have less error handling code.

However, if you intend to add additional checks / wrappings around that authentication call, then you should have your Model make the call. So if there is a likely additional call for authorization after the authentication check, then I would lean towards calling from the Model.


Quick note, loose definitions:
Authentication: "Am I who I say I am?"
Authorization: "Do I have the authority or permission to access this?"