title: How to get current user in every request in Spring Boot?
body: <p>I would like to get the username of the user in every request to add them to log file.</p>
  
  <p><strong>This is my solution:</strong></p>
  
  <p>First, I created a <code>LoggedUser</code> with a <code>static</code> property:</p>
  
  <pre class="lang-java prettyprint-override"><code>public class LoggedUser {
  
      private static final ThreadLocal&lt;String&gt; userHolder = 
          new ThreadLocal&lt;&gt;();
  
      public static void logIn(String user) {
          userHolder.set(user);
      }
  
      public static void logOut() {
          userHolder.remove();
      }
  
      public static String get() {
          return userHolder.get();
      }
  }
  </code></pre>
  
  <p>Then I created a support class to get username:</p>
  
  <pre class="lang-java prettyprint-override"><code>public interface AuthenticationFacade {
      Authentication getAuthentication();
  }
  </code></pre>
  
  <pre class="lang-java prettyprint-override"><code>@Component
  public class AuthenticationFacadeImpl implements AuthenticationFacade {
      @Override
      public Authentication getAuthentication() {
          return SecurityContextHolder.getContext().getAuthentication();
      }
  }
  </code></pre>
  
  <p>Finally, I used them in my Controllers:</p>
  
  <pre class="lang-java prettyprint-override"><code>    @RestController
      public class ResourceController {
  
          Logger logger = LoggerFactory.getLogger(ResourceController.class);
  
          @Autowired
          private GenericService userService;
          @Autowired
          private AuthenticationFacade authenticationFacade;
  
          @RequestMapping(value ="/cities")
          public List&lt;RandomCity&gt; getCitiesAndLogWhoIsRequesting(){
          loggedUser.logIn(authenticationFacade.getAuthentication().getName());
          logger.info(LoggedUser.get()); //Log username
          return userService.findAllRandomCities();
          }
      }
  </code></pre>
  
  <p>The problem is I don't want to have <code>AuthenticationFacade</code> in every <code>@Controller</code>, If I have 10000 controllers, for example, it will be a lot of works.</p>
  
  <p>Do you have any better solution for it?</p>