title: Best practice to make sure an AUTHENTICATED user is AUTHORISED to access a resource - Spring mvc, Spring Security, Hibernate
body: <p>We have a spring mvc rest api, utilising spring security and hibernate to a MySql db.</p>
  
  <p>We have some roles configured. For example:</p>
  
  <p>Standard user: <strong>ROLEA</strong></p>
  
  <p>Super user: <strong>ROLEB</strong></p>
  
  <p>Currently to ensure that an <strong>authenticated</strong> user is <strong>authorised</strong> to access/update a certain resource we do something like this:</p>
  
  <p>Identify the current authenticated user:</p>
  
  <pre><code>Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  String activeLogin = authentication.getName();
  </code></pre>
  
  <p>Identify the login associated with the entity they are trying to access:</p>
  
  <pre><code>String loginAssociatedToRequestedEntity = fooService.getEntityA(EntityAId).getEntityB().getEntityC().getLogin();
  </code></pre>
  
  <p>Compare the user associated with given resource to active login:</p>
  
  <pre><code>if (!loginAssociatedToRequestedEntity.equals(activeLogin)) { 
  throw new ForbiddenAccessException();
  }
  </code></pre>
  
  <p>I have a number of issues with this, some of these include:</p>
  
  <ul>
  <li>Very wasteful… each entity would have to be hydrated/populated. This could be even worse than the above example if the entity to be accessed is further away from the table with the login names in.</li>
  <li>Seems like a code smell (Law of Demeter).</li>
  <li>A request may come in that could update multiple entities. A similar check to the above may have to be repeated.</li>
  </ul>
  
  <p>I have considered the following as possible options:</p>
  
  <p><a href="http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#domain-acls" rel="noreferrer">Spring ACLs</a></p>
  
  <p><a href="http://shiro.apache.org/" rel="noreferrer">Apache shiro</a></p>
  
  <p>So my question is, is there a best practice to make sure an <strong>authenticated</strong> user is <strong>authorised</strong> to access a certain resource i.e. stopping them from accessing a resource of another user in the same role.</p>
  
  <p>If you could point out a concrete example (github) that would be much appreciated.</p>
  
  <p>TIA.</p>