title: Spring Security pre-authentication - gives me a new session even though principal is unchanged
body: <p>I have implemented a spring security preathentication filter in my Grails application in order to integrate with Tivoli Access Manager.</p>
  
  <p>The filter getting called for every request in my web application - yet even though the filter returns the same principal as a previous request, it seems to create a new session. I have created a ApplicationListener to listen for authentication events and I can see a new AuthenticationSuccessEvent, with a new session id for each request.</p>
  
  <p>This means all my session variables get cleared each request- which wouldn't be a big deal but it breaks the uploadr plugin.</p>
  
  <p>When I turn debug logging on for my preauthentication filter I see that it thinks the principal has changed, even though it has not:</p>
  
  <pre><code>2015-03-04 11:34:57.769 foobar.TamAuthenticationFilter Checking secure context token: org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken@f0666480: Principal: grails.plugin.springsecurity.userdetails.GrailsUser@3125618: Username: 66734; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN,ROLE_APPROVER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 87928D9E25D98DD3CCFAC5D67689E609; Granted Authorities: ROLE_ADMIN, ROLE_APPROVER
  2015-03-04 11:34:57.770 foobar.TamAuthenticationFilter Pre-authenticated principal has changed to 66734 and will be reauthenticated
  2015-03-04 11:34:57.770 foobar.TamAuthenticationFilter Invalidating existing session
  2015-03-04 11:34:57.771 foobar.TamAuthenticationFilter preAuthenticatedPrincipal = 66734, trying to authenticate
  </code></pre>
  
  <p>How can I make spring security use the same session for each principal returned by the pre authentication filter, rather than create a new one for every request?</p>
  
  <p>here is my filter:</p>
  
  <pre><code>package foobar
  
  import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter
  import grails.util.Environment
  import grails.util.Holders
  import groovy.util.logging.Log4j
  
  @Log4j
  class TamAuthenticationFilter extends   AbstractPreAuthenticatedProcessingFilter {
  
  java.lang.Object getPreAuthenticatedCredentials(javax.servlet.http.HttpServletRequest request)
  {
      "N/A"
  }
  
  java.lang.Object getPreAuthenticatedPrincipal(javax.servlet.http.HttpServletRequest request)
  {
      Long staffId = getStaffIdFromTamHeader(request)
      if(!staffId)
          log.error "iv-user header not found"
  
      return staffId
  }
  
  /**
   * Get Staff ID from the ivUser Tamheader.
   * @param request
   * @return
   */
  static public Long getStaffIdFromTamHeader(request) {
      return request.getHeader("iv-user")
  }
  
  }
  </code></pre>
  
  <p>LoggingSecurityEventListener:</p>
  
  <pre><code> package foobar
  
   import groovy.util.logging.Log4j
   import org.springframework.context.ApplicationListener
   import org.springframework.security.authentication.event.AbstractAuthenticationEvent
  
  
   @Log4j
   class LoggingSecurityEventListener implements
      ApplicationListener&lt;AbstractAuthenticationEvent&gt; {
  
  void onApplicationEvent(AbstractAuthenticationEvent event) {
  
      def username = event.authentication.principal
      def address = event.authentication.details.remoteAddress
      def sessionId = event.authentication.details.sessionId
  
      log.info "event=${event.class.simpleName} username=${username} remoteAddress=${address} sessionId=${sessionId}"
  
  }
  
   }
  </code></pre>
  
  <p>resources.groovy:</p>
  
  <pre><code>beans = {
  //
  // grabs the user id from the tam headers 
  //
  tamAuthenticationFilter(TamAuthenticationFilter) {
      authenticationManager = ref('authenticationManager')
      checkForPrincipalChanges = true
  }
  
  tamAuthenticationProvider(PreAuthenticatedAuthenticationProvider) {
     preAuthenticatedUserDetailsService = ref('authenticationUserDetailsService')
  }
  
  //
  // we do not want to redirect to the auth/login page since we are using tam
  //
  authenticationEntryPoint(Http403ForbiddenEntryPoint)
  
  securityEventListener(LoggingSecurityEventListener)
  }
  </code></pre>
  
  <p>config.groovy:</p>
  
  <pre><code> grails.plugin.springsecurity.useSecurityEventListener = true
   grails.plugin.springsecurity.providerNames = ['tamAuthenticationProvider']
  
   grails.plugin.springsecurity.userLookup.userDomainClassName = 'strobe.auth.User'
   grails.plugin.springsecurity.userLookup.authorityJoinClassName = 'strobe.auth.UserRole'
   grails.plugin.springsecurity.authority.className = 'strobe.auth.Role'
   grails.plugin.springsecurity.securityConfigType="InterceptUrlMap"
   grails.plugin.springsecurity.interceptUrlMap = [
                                              '/foobar/**':                   ['ROLE_USER']]
  </code></pre>
  
  <p>bootstrap.groovy:</p>
  
  <pre><code> def init = { servletContext -&gt;                   SpringSecurityUtils.clientRegisterFilter('tamAuthenticationFilter',
              SecurityFilterPosition.PRE_AUTH_FILTER.order + 10)
   }
  </code></pre>