Java MVC – Role-Based Access Control Model in Object-Oriented Programming

javamvc

I want to prepare a swing application. I am designing a role based access control model in mvc design.

When a view wants to request something from a controller, how can this request be realized in object oriented manner. That is, while requesting how can session information of user be sent to the model or controller?

For example, a model method can be like that

createCustomeraccount(EntityCustomer obj, Session user)

so all methods in model classes should have session object parameter which has role information of user and also role and rights should be store in a class to check user right. Therefore every model has a roleright object which includes role and right mapping.

Is this correct design?

Best Answer

It will probably be a lot easier for you if you don't have to pass the Session to every method call on a controller. This puts the requirement for keeping the Session on the view and that's not really where it belongs. It also makes your controller methods very heavy as they will need to always have this parameter, even if it makes no sense.

Instead, why not set up this 'session' when the user logs into the application and make it available through a class? In the simplest model your controller could have a 'SessionContext' or 'UserContext' injected in the constructor and every method could call that context and validate authorization to call the method, throwing exceptions if the requirements are not met.

public class CustomerController
{
    private UserContext _context;

    public CustomerController(UserContext context)
    {
            _context = context;
    }

    public void createCustomerAccount(EntityCustomer obj)
    {
        if(!_context.isUserAdmin())
            throw new UnauthorizedMethodException("User not authorized to call createCustomerAccount");

        //do your thing
    }   
}

(Not Java, but you get the idea)

More advanced ways of doing this could include using a Command Object-driven approach or using Aspects on methods.