Search code examples
javasecuritydomain-driven-designauthorization

Restrict access to the owner of an object in DDD


Let's say there is an object TaskList which can be edited and deleted only by its owner. Other users should only by able to take a task and update its status.

The following options come to my mind:

  • check the ownership and access in the controller of the web application
  • let the repository return proxy object which throws exception on certain operations, but the controller (or view) would still need to know which actions (in form of links or form fields) should be visible
  • pass the caller (user) to the method of the domain object, so that the domain object can itself check whether the caller ist allowed or not.

The used technology is Java.

Any other/better ideas?

Interesting articles about security and DDD

I have accepted my own answer now, because that is what I actually use, but further suggestions are welcome.


Solution

  • I found it unnecessarily complex to create accessor classes for each protected domain class as suggested by 'Gray'. My solution is probably not perfect, but simple to use and - more important - robust. You cannot forget to use a certain object or to check conditions outside.

    public class TaskList {
    
        private SystemUser owner;
        private List<Task> tasks = new ArrayList<>();
    
        public TastList(SystemUser owner) {
            this.owner = owner;
        }
    
        public void Add(Task task) {
            Guard.allowFor(owner); 
            tasks.add(task);
        }
    }
    

    The Guard knows the current user (from a thread local for example) and compares it to the owner passed as parameter to allowFor(owner). If access is denied a security exception will be thrown.

    That is simple, robust and even easy to maintain since only the guard has to be changed if the underlying authentication changes.