title: Spring boot create a custom annotation to get logged in user?
body: <p>I have a entity model called <code>User</code>. I have implemented <code>UserDetailsService</code> and used it in WebSecurityConfig like this. Removed unnecessary code for brevity.</p>
  
  <pre><code>@Configuration
  @EnableWebSecurity
  @EnableGlobalMethodSecurity(prePostEnabled = true)
  public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
      @Override
      public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
          authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
      }
  
      @Bean
      @Override
      public AuthenticationManager authenticationManagerBean() throws Exception {
          return super.authenticationManagerBean();
      }
  }
  </code></pre>
  
  <p>Now at any place during a request-response, I can use this code to get the currently logged in user</p>
  
  <pre><code>Authentication auth = SecurityContextHolder.getContext().getAuthentication();
  String username = auth.getName();
  // now use some jpa logic to retrive User entity using above username
  </code></pre>
  
  <p>Now my question is, is there any way to create a custom AOP or annotation that gives me access to logged in user so that I can use it anywhere like in my controller as shown below?</p>
  
  <pre><code>public class LoginController {
      public String response(@CurrentUser User user) {
          // do logic once you have access to logged in user with help of @CurrentUser annotation
      }
  }
  </code></pre>
  
  <p>So like in the above example, can I create an annotation <code>@CurrentUser</code> that gives me currently logged in user(if not throws an exception, which I can catch in controller advice)?</p>
  
  <p>Note: How I get the user is up to me. In the above example I am using authentcation.getName() and then querying my db to build User entity. But I can use any other way to do so. I just want to create an annotation like CurrentUser and then add the code (of retrieving the user) behind it.</p>