title: Spring Boot authorisation in services
body: <p>I have a Spring Boot application which uses Spring Security to Authenticate and Authorise requests using a JWT. However, some requests should only be able to be executed by a particular user. For example:</p>
  
  <p><code>GET /users/{id}/orders</code> should only return the list of orders if <code>{id}</code> is the current user or the current user is <code>ADMIN</code></p>
  
  <p><code>PUT /orders/{id}</code> should only edit the order if the its <code>payer</code> is the current user</p>
  
  <p><code>PUT /representation-requests/{id}/accept</code> should only work if the current user is the <code>target</code> of the representation request</p>
  
  <p>Because of the usage of JWTs, the way I get the current user's ID is by </p>
  
  <p><code>String userId = ((DecodedJWT) SecurityContextHolder.getContext().getAuthentication().getDetails()).getSubject();</code></p>
  
  <p>I've implemented this in the various methods of the services responsible for handling each API call. My question is if there is a more general way to do this using Spring Boot and Spring Security? Or is this not a standard use case?</p>
  
  <p>I have looked at <code>@PreAuthorize</code> annotation in controllers, but it does not suite my needs as the URL parameters are not enough to check the nested entities. <code>@PostAuthorize</code> in controllers seems closer, but because of the JWT I couldn't get it to work (and it also seems a bit clunky to do long code in annotations, not sure it is better than doing it in the service itself). I appreciate a pointer in the right direction.</p>