MultiUserEnvironmentInitializationFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { Subject sessionSubject; HttpServletRequest httpRequest = (HttpServletRequest) request; final String token = tokenExtractor.getToken(httpRequest); if (token == null) { handleMissingToken(request, response, chain); return; } String userId = getUserId(token); httpRequest = new SessionCachedHttpRequest(request, userId); HttpSession session = httpRequest.getSession(true); sessionSubject = (Subject) session.getAttribute(CHE_SUBJECT_ATTRIBUTE); if (sessionSubject == null) { sessionSubject = extractSubject(token); session.setAttribute(CHE_SUBJECT_ATTRIBUTE, sessionSubject); } else if (!sessionSubject.getUserId().equals(userId)) { LOG.debug( "Invalidating session with mismatched user IDs: old was '{}', new is '{}'.", sessionSubject.getUserId(), userId); session.invalidate(); HttpSession new_session = httpRequest.getSession(true); sessionSubject = extractSubject(token); new_session.setAttribute(CHE_SUBJECT_ATTRIBUTE, sessionSubject); } else if (!sessionSubject.getToken().equals(token)) { sessionSubject = extractSubject(token); session.setAttribute(CHE_SUBJECT_ATTRIBUTE, sessionSubject); } try { EnvironmentContext.getCurrent().setSubject(sessionSubject); chain.doFilter(new SubjectHttpRequestWrapper(httpRequest, sessionSubject), response); } finally { EnvironmentContext.reset(); } } MultiUserEnvironmentInitializationFilter(
      SessionStore sessionStore, RequestTokenExtractor tokenExtractor); @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain);  }
@Test public void shouldSetSubjectIntoEnvironmentContext() throws Exception { EnvironmentContext context = spy(EnvironmentContext.getCurrent()); EnvironmentContext.setCurrent(context); when(tokenExtractor.getToken(any(HttpServletRequest.class))).thenReturn(token); when(sessionStore.getSession(eq(userId), any())).thenReturn(session); when(session.getAttribute(eq(CHE_SUBJECT_ATTRIBUTE))).thenReturn(subject); filter.doFilter(request, response, chain); verify(context).setSubject(eq(subject)); }