title: How to get current user in interceptors and retrieve its resources in controllers
body: <p>I'm developing a Spring MVC project and I want to implement my own authentication interceptor. It looks like this:</p>
  
  <pre><code>@Component
  public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
  
      @Autowired
      private UsersRepo usersRepo;
  
      @Override
      public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
          if (!(handler instanceof HandlerMethod)) return true;
          HandlerMethod handlerMethod = (HandlerMethod) handler;
  
          if (handlerMethod.getMethodAnnotation(Authenticated.class) == null) return true;
  
          HttpSession session = request.getSession(false);
          if (session == null) return reject(response);
  
          Long id = (Long) session.getAttribute("userId");
          if (id == null) return reject(response);
  
          User user = usersRepo.findOne(id);
          if (user == null) return reject(response);
  
          RequestContext.CURRENT_USER.set(user);
  
          return true;
      }
  
      @Override
      public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
          RequestContext.CURRENT_USER.remove();
      }
  
      private boolean reject(HttpServletResponse response) {
          response.setStatus(403);
          return false;
      }
  }
  </code></pre>
  
  <p><code>RequestContext.CURRENT_USER</code> is a <code>ThreadLocal&lt;User&gt;</code>.</p>
  
  <p>In the controller, I want to retrieve orders of the current user:</p>
  
  <pre><code>@RestController
  @RequestMapping("/orders")
  public class OrdersController {
  
      @RequestMapping(method = RequestMethod.GET)
      @Authenticated
      public Collection&lt;Order&gt; index() {
          Collection&lt;Order&gt; orders = RequestContext.CURRENT_USER.get().getOrders();
          return orders;
      }
  
  }
  </code></pre>
  
  <p>It gives me <code>Could not write content: failed to lazily initialize a collection of role: myapp.models.User.orders, could not initialize proxy - no Session</code>.</p>
  
  <p>I think that's because Hibernate has closed the database session when it's done the job finding the current <code>User</code> in the interceptor, and thus it's unable to use that <code>User</code> to load <code>Order</code>s in another session. But I really don't want to hit database again. How can I load current user in interceptor and reuse that user instance to load more resources?</p>