title: Authentication using custom AbstractAuthenticationProcessingFilter and custom CustomAuthenticationProvider is not working propertly
body: <p>We are using spring security to authenticate the user based on some user details (like userid ) coming from external application and perform authorization using the security context holder. We are using custom implementation of AbstractAuthenticationProcessingFilter and custom implemtation of CustomAuthenticationProvider with our own UserDetailsServiceImpl injected into provider for fetching user details from db. </p>
  
  <p>When single user tries to login it works fine, authentication object is created and it is properly set into SecurityCOntextHolder. But when another user tries to login the old authentication objects gets overwritten by new one. Looks like new session is not created on each user login. </p>
  
  <p>The implementation for the filter and provider is like below --</p>
  
  <pre><code>    public class DefaultAuthenticationProcessingFilter extends
      AbstractAuthenticationProcessingFilter {
  
  private final static Logger logger = LoggerFactory.getLogger(DefaultAuthenticationProcessingFilter.class);
  
  private static final String INTERCEPTOR_PROCESS_URL = "/sso/landingpage.action";
  
  public DefaultAuthenticationProcessingFilter() {
      super(INTERCEPTOR_PROCESS_URL);
  }
  
  public DefaultAuthenticationProcessingFilter(
          String defaultFilterProcessesUrl) {
      super(defaultFilterProcessesUrl);
      Assert.notNull(defaultFilterProcessesUrl, "Configuration error :: DefaultFilterProcessesUrl must be specified");
  }
  
  
  /**
   * Method to do authentication of user
   */
  @Override
  public Authentication attemptAuthentication(HttpServletRequest request,
          HttpServletResponse response) throws AuthenticationException,
          IOException, ServletException {
  
      logger.info("Authenticating the user .....");
  
      Authentication authResult = null;
      try {
  
          String eid = request.getParameter("EID");
  
          if( StringUtils.isEmpty(eid)) {
               throw new PreAuthenticatedCredentialsNotFoundException("EID param not found in request.");
          }
  
          String credentials = "NA";
          PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken(eid, credentials);
          authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
          authResult = getAuthenticationManager().authenticate(authRequest);
      } catch (AuthenticationException e) {
          unsuccessfulAuthentication(request, response, e);
      } 
      return authResult;
  }
      }
  
  
      protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
              Authentication authResult) throws IOException, ServletException {
  
          if (logger.isDebugEnabled()) {
              logger.debug("Authentication success. Updating SecurityContextHolder to contain: " + authResult);
          }
  
          SecurityContextHolder.getContext().setAuthentication(authResult);
  
          getRememberMeServices().loginSuccess(request, response, authResult);
  
          // Fire event
          if (this.eventPublisher != null) {
              eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass()));
          }
  
          getSuccessHandler().onAuthenticationSuccess(request, response, authResult);
   }
      }
  </code></pre>
  
  <p>The implementation of custom provider is as below - </p>
  
  <pre><code>    public class CustomAuthenticationProvider implements AuthenticationProvider, InitializingBean {
  
  private final static Logger logger = LoggerFactory.getLogger(CustomAuthenticationProvider.class);
  
  private AuthenticationUserDetailsService&lt;PreAuthenticatedAuthenticationToken&gt; preAuthenticatedUserDetailsService = null;
  /**
  * 
  */
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  
      if (!supports(authentication.getClass())) {
          return null;
      }
  
      if (logger.isDebugEnabled()) {
          logger.debug("PreAuthenticated authentication request: " + authentication);
      }
  
      if (authentication.getPrincipal() == null) {
          logger.debug("No pre-authenticated principal found in request.");
          return null;
      }
  
      UserDetails ud = preAuthenticatedUserDetailsService.loadUserDetails((PreAuthenticatedAuthenticationToken)authentication);
  
      PreAuthenticatedAuthenticationToken result =
              new PreAuthenticatedAuthenticationToken(ud, authentication.getCredentials(), ud.getAuthorities());
      result.setDetails(authentication.getDetails());
  
      return result;
  
  }
  
  @Override
  public void afterPropertiesSet() throws Exception {
      // TODO Auto-generated method stub
  }
  
  @Override
  public boolean supports(Class&lt;?&gt; authentication) {
      return PreAuthenticatedAuthenticationToken.class.isAssignableFrom(authentication);
  }
  
  /**
   * @return the preAuthenticatedUserDetailsService
   */
  public AuthenticationUserDetailsService&lt;PreAuthenticatedAuthenticationToken&gt; getPreAuthenticatedUserDetailsService() {
      return preAuthenticatedUserDetailsService;
  }
  
  /**
   * @param preAuthenticatedUserDetailsService the preAuthenticatedUserDetailsService to set
   */
  public void setPreAuthenticatedUserDetailsService(
          AuthenticationUserDetailsService&lt;PreAuthenticatedAuthenticationToken&gt; preAuthenticatedUserDetailsService) {
      this.preAuthenticatedUserDetailsService = preAuthenticatedUserDetailsService;
  }
  }
  </code></pre>
  
  <p>We have also configures custom authentication success handler to redirect user to appropriate URL upon authentication -</p>
  
  <pre><code>    public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
  
  /**
   * redirect user to appropriate home page based on user role
   */
  @Override
  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
  
      Set&lt;GrantedAuthority&gt; authorities = ((UserDetails)authentication.getPrincipal()).getAuthorities();
      if(CollectionUtils.isNotEmpty(authorities)){
          GrantedAuthority role = getHighestRole(authorities);
          String targetURL = getTargetURL(role);
          if (targetURL != null) {
              log.debug("Redirecting to target Url: " + targetURL);
              getRedirectStrategy().sendRedirect(request, response, targetURL);
              return;
          }
      }
  
      super.onAuthenticationSuccess(request, response, authentication);
  
  }
    }
  </code></pre>
  
  <p>The spring security config file is like below -</p>
  
  <pre><code>    &lt;?xml version="1.0" encoding="UTF-8"?&gt;
      &lt;beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:security="http://www.springframework.org/schema/security"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
                         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                         http://www.springframework.org/schema/security
                         http://www.springframework.org/schema/security/spring-security-3.1.xsd"&gt;
  
   &lt;security:http use-expressions="true" auto-config="false" pattern="/sso/*" entry-point-ref="http403ForbiddenEntryPoint" access-denied-page="/accessdenied.action" &gt;
      &lt;security:anonymous enabled="false"/&gt;
      &lt;security:custom-filter position="BASIC_AUTH_FILTER" ref="defaultBasicAuthFilter" /&gt;
      &lt;security:expression-handler ref="expressionHandler"/&gt;
  &lt;/security:http&gt;
  
  &lt;security:http use-expressions="true" auto-config="false" pattern="/rcd/associate/*" entry-point-ref="http403ForbiddenEntryPoint"  access-denied-page="/accessdenied.action"&gt;
      &lt;security:intercept-url pattern="/saml/sso/*" access="IS_AUTHENTICATED_ANONYMOUSLY"/&gt;
          &lt;security:custom-filter position="BASIC_AUTH_FILTER" ref="defaultBasicAuthFilter" /&gt;
      &lt;security:expression-handler ref="expressionHandler"/&gt;
  &lt;/security:http&gt;
  
  &lt;bean id="http403ForbiddenEntryPoint"
      class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint" /&gt;
  
  
  &lt;bean id="expressionHandler" class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler"&gt;
       &lt;property name="permissionEvaluator" ref="customPermissionEvaluator" /&gt; 
  &lt;/bean&gt;
  
  &lt;bean id="defaultBasicAuthFilter"
      class="com.example.security.authentication.DefaultAuthenticationProcessingFilter"&gt;
      &lt;property name="authenticationManager" ref="authenticationManager" /&gt;
      &lt;property name="authenticationSuccessHandler" ref="successRedirectHandler"/&gt;
      &lt;property name="AuthenticationFailureHandler" ref="failureHandler"&gt;&lt;/property&gt;
  &lt;/bean&gt;
  
  &lt;bean id="authProvider"
  class="com.example.security.authentication.CustomAuthenticationProvider"&gt;
      &lt;property name="preAuthenticatedUserDetailsService"&gt;
          &lt;bean id="userDetailsServiceWrapper"
              class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper"&gt;
              &lt;property name="userDetailsService" ref="userDetailsService" /&gt;
          &lt;/bean&gt;
      &lt;/property&gt;
  &lt;/bean&gt;
  
  &lt;security:authentication-manager alias="authenticationManager"&gt;
      &lt;security:authentication-provider
          ref="authProvider" /&gt;
  &lt;/security:authentication-manager&gt;
  
  &lt;bean id="userDetailsService" class="com.example.security.authorization.UserDetailsServiceImpl" /&gt;
  
   &lt;bean id="successRedirectHandler"
        class="com.example.security.authentication.CustomAuthenticationSuccessHandler"&gt;
          &lt;property name="defaultTargetUrl" value="/user1/user1LandingPage.action"/&gt;
       &lt;/bean&gt;
  
  &lt;bean id="failureHandler"
        class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"&gt;
      &lt;property name="defaultFailureUrl" value="/accessdenied.action"/&gt;
  &lt;/bean&gt;
  </code></pre>
  
  <p></p>
  
  <p>We have also configured web.xml </p>
  
  <pre><code>&lt;listener&gt;
      &lt;listener-class&gt;
          org.springframework.web.context.ContextLoaderListener
      &lt;/listener-class&gt;
  &lt;/listener&gt;
  
  &lt;context-param&gt;
      &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
      &lt;param-value&gt;
          /WEB-INF/spring/spring-app-context.xml &lt;!-- ,/WEB-INF/spring/security.xml --&gt;
      &lt;/param-value&gt;
  &lt;/context-param&gt;
  
  &lt;servlet&gt;
      &lt;servlet-name&gt;example-dispatcher-servlet&lt;/servlet-name&gt;
      &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
      &lt;init-param&gt;
          &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
          &lt;param-value&gt;/WEB-INF/spring/mvc.xml&lt;/param-value&gt;
      &lt;/init-param&gt;
      &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
  &lt;/servlet&gt;
  
  &lt;!-- Map all /example*.action requests to the example-dispatcher-servlet for handling --&gt;
  &lt;servlet-mapping&gt;
      &lt;servlet-name&gt;example-dispatcher-servlet&lt;/servlet-name&gt;
      &lt;url-pattern&gt;*.action&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
  
  &lt;welcome-file-list&gt;
      &lt;welcome-file&gt;/rcd/pages/index.jsp&lt;/welcome-file&gt;
  &lt;/welcome-file-list&gt;
  
  &lt;listener&gt;
      &lt;listener-class&gt;com.example.HttpSessionListenerImpl&lt;/listener-class&gt;
  &lt;/listener&gt;
  
  
  &lt;!-- Spring Security --&gt;
  &lt;filter&gt;
      &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
      &lt;filter-class&gt;org.springframework.web.filter.DelegatingFilterProxy&lt;/filter-class&gt;
  &lt;/filter&gt;
  
  &lt;filter-mapping&gt;
    &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
    &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
  &lt;/filter-mapping&gt;
  &lt;/web-app&gt;
  </code></pre>
  
  <p>We are using spring 3.1.3 and spring security 3.1.3
  On each user login new session should be created and security context should be set accordingly. But its happening in my case. I checked debuggin my application and found that new session is not getting created on user login. May be i am missing it somewhere. I don't find any relevant solution anywhere.</p>
  
  <p>Any help in this regard will be appreciated the most. </p>
  
  <p>Thanks.</p>