title: Spring REST Api -- access User details in repository
body: <p>The setup of the RESPApi project is: </p>
  
  <ul>
  <li>SpringBoot</li>
  <li>Spring's OAuth2</li>
  </ul>
  
  <p>In the project we have many clients, so SQL queries almost always have <code>"... and clientId = ?"</code> in the <code>where</code> clause. </p>
  
  <p>We store <code>clientId</code> in the <code>SecurityContext</code> with other user details (we extend Spring's <code>User</code> class). </p>
  
  <p>The question is: how to get the <code>User</code> object in the <code>@Repository</code>?</p>
  
  <p>Possible solutions we can think of: </p>
  
  <ol>
  <li>In every repository implementation add</li>
  </ol>
  
  <p><code>SecurityContextHolder.getContext().getAuthentication()</code></p>
  
  <p>cast the result to our custom UserDetails implementation and use it.</p>
  
  <p>Cons: somehow I feel there's a better solution.</p>
  
  <ol start="2">
  <li>Add <code>@AuthenticationPrincipal</code> annotated parameters to the controllers and then pass the parameters to the service layer and then to the repository layer. </li>
  </ol>
  
  <p>Cons: passing the paremeter though 2 layers only to obtain <code>clientId</code> doesn't seem reasonable.</p>
  
  <p>I thought about <code>@Autowired</code> paramter <code>MyUser user</code> in the <code>@Repository</code> class. The first try was to create <code>@Configuration</code> annotated class in which there will be a method </p>
  
  <pre><code>    @Bean
  public MyUser getUser() {
      SecurityContext context = SecurityContextHolder.getContext();
      if (context != null) {
          Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
          if (authentication != null) {
              return (MyUser) authentication.getPrincipal();
          }
      }
      return null;
  }
  </code></pre>
  
  <p>But the bean is null and I cannot use it. </p>
  
  <p>For now we've ended up with solution nr 1 but I feel there must be a better way.</p>
  
  <p>Any ideas how to solve this problem?</p>