title: An Authentication object was not found in the SecurityContext - Spring 3.2.2
body: <p>I'm trying to invoke a protected method from a class that implements the <code>ApplicationListener&lt;AuthenticationSuccessEvent&gt;</code> interface on successful login (Spring 3.2.2 and Spring Security 3.2.0 M1). <a href="https://stackoverflow.com/q/15493237/1391249">This</a> is my previous question.</p>
  
  <p>The application runs under the following environment.</p>
  
  <ul>
  <li>Spring 3.2.2</li>
  <li>Spring Security 3.2.0</li>
  <li>JPA 2.0</li>
  <li>JSF 2.1.9</li>
  <li>MySQL 5.6.11</li>
  <li>JDK-7u11</li>
  <li>NetBeans 7.2.1</li>
  </ul>
  
  <p>I have added the following libraries related to Spring security to the classpath.</p>
  
  <ul>
  <li>spring-security-core-3.2.0.M1.jar</li>
  <li>spring-security-config-3.2.0.M1.jar</li>
  <li>spring-security-web-3.2.0.M1.jar</li>
  </ul>
  
  <hr>
  
  <p>The class that implements <code>ApplicationListener&lt;AuthenticationSuccessEvent&gt;</code> is as follows.</p>
  
  <pre><code>package loginsuccesshandler;
  
  import admin.dao.service.StateService;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.context.ApplicationListener;
  import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
  import org.springframework.stereotype.Service;
  
  @Service
  public final class AuthSuccessHandler implements ApplicationListener&lt;AuthenticationSuccessEvent&gt;
  {
      @Autowired
      private StateService stateService;
  
      @Override
      public void onApplicationEvent(AuthenticationSuccessEvent event) 
      {
          System.out.println(event.getAuthentication());
          System.out.println("rowCount = "+stateService.rowCount());
      }
  }
  </code></pre>
  
  <p>This prevents a user from being logged in even with correct credentials with the following message (it is just an example. Counting the number of states upon successful authentication is not required at all).</p>
  
  <blockquote>
    <p>An Authentication object was not found in the SecurityContext</p>
  </blockquote>
  
  <hr>
  
  <p>The event is raised. The first statement inside the <code>onApplicationEvent()</code> method displays the following.</p>
  
  <pre><code>org.springframework.security.authentication.UsernamePasswordAuthenticationToken@45264a59: Principal: org.springframework.security.core.userdetails.User@586034f:Username: admin; 
  Password: [PROTECTED]; 
  Enabled: true; 
  AccountNonExpired: true; 
  credentialsNonExpired: true; 
  AccountNonLocked: true; 
  Granted Authorities: ROLE_ADMIN; 
  Credentials: [PROTECTED]; 
  Authenticated: true; 
  Details: org.springframework.security.web.authentication.WebAuthenticationDetails@380f4: RemoteIpAddress: 127.0.0.1; 
  SessionId: 88777A678DC5BB0272F84CA4BC61FAF2;
  Granted Authorities: ROLE_ADMIN
  </code></pre>
  
  <p>So it appears that the user is authenticated and the authentication object is available.</p>
  
  <hr>
  
  <p>My <code>springSecurity.xml</code> file simply looks like the following.</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
             http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
             http://www.springframework.org/schema/security
             http://www.springframework.org/schema/security/spring-security-3.1.xsd"&gt;
  
      &lt;http pattern="/utility/Login.jsf*" security="none"/&gt;
      &lt;debug/&gt;
      &lt;http auto-config='true' use-expressions="true" disable-url-rewriting="true"&gt;
          &lt;session-management session-fixation-protection="newSession"&gt;
              &lt;concurrency-control max-sessions="1" error-if-maximum-exceeded="true" /&gt;
          &lt;/session-management&gt;
  
          &lt;intercept-url pattern="/admin_side/**" access="hasRole('ROLE_ADMIN')" requires-channel="any"/&gt;
          &lt;intercept-url pattern="/utility/Login.jsf" access="permitAll" requires-channel="any"/&gt;
          &lt;http-basic /&gt;
          &lt;anonymous /&gt;
  
          &lt;form-login login-processing-url="/j_spring_security_check" login-page="/utility/Login.jsf" authentication-success-handler-ref="loginSuccessHandler" authentication-failure-handler-ref="authenticationFailureHandler"/&gt;
          &lt;logout logout-success-url="/utility/Login.jsf" invalidate-session="true" delete-cookies="JSESSIONID"/&gt;
      &lt;/http&gt;
  
      &lt;authentication-manager&gt;
         &lt;authentication-provider&gt;
              &lt;jdbc-user-service data-source-ref="dataSource"
                 users-by-username-query="select email_id, password, enabled from user_table where lower(email_id)=lower(?)"
                 authorities-by-username-query="select ut.email_id, ur.authority from user_table ut, user_roles ur where ut.user_id=ur.user_id and lower(ut.email_id)=lower(?)"/&gt;
         &lt;/authentication-provider&gt;
      &lt;/authentication-manager&gt;
  
      &lt;beans:bean id="loginSuccessHandler" class="loginsuccesshandler.LoginSuccessHandler"/&gt;
      &lt;beans:bean id="authenticationFailureHandler" class="loginsuccesshandler.AuthenticationFailureHandler" /&gt;        
  
      &lt;global-method-security secured-annotations="enabled" pre-post-annotations="enabled" proxy-target-class="false"&gt;
          &lt;protect-pointcut expression="execution(* admin.dao.*.*(..))" access="ROLE_ADMIN"/&gt;
      &lt;/global-method-security&gt;
  &lt;/beans:beans&gt;
  </code></pre>
  
  <hr>
  
  <p>The Spring security works fine, when the following lines of XML is omitted from the <code>spring-security.xml</code> file.</p>
  
  <pre><code>&lt;global-method-security secured-annotations="enabled" proxy-target-class="false"&gt;
       &lt;protect-pointcut expression="execution(* admin.dao.*.*(..))" access="ROLE_ADMIN"/&gt;
  &lt;/global-method-security&gt;
  </code></pre>
  
  <p>Can a protected method (with method security applied) be invoked from a class implementing the <code>ApplicationListener&lt;AuthenticationSuccessEvent&gt;</code> interface? If yes, then what is missing in my case? I have clicked thousands of links so far but couldn't find a single clue.</p>
  
  <hr>
  
  <p>The <code>application-context.xml</code> file.</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:p="http://www.springframework.org/schema/p"
         xmlns:aop="http://www.springframework.org/schema/aop"
         xmlns:tx="http://www.springframework.org/schema/tx"
         xmlns:context="http://www.springframework.org/schema/context"
         xmlns:jee="http://www.springframework.org/schema/jee"
         xmlns:mvc="http://www.springframework.org/schema/mvc"
         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
         http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"&gt;
  
      &lt;context:component-scan base-package="admin.mangedbean loginsuccesshandler" use-default-filters="false"&gt;
          &lt;context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/&gt;
          &lt;context:include-filter expression="org.springframework.web.bind.annotation.ControllerAdvice" type="annotation"/&gt;  
      &lt;/context:component-scan&gt;
  
      &lt;mvc:annotation-driven/&gt;
      &lt;context:annotation-config/&gt;
  
      &lt;bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/&gt;            
  
      &lt;bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory" &gt;
          &lt;property name="jpaProperties"&gt;
              &lt;props&gt;
                  &lt;prop key="hibernate.enable_lazy_load_no_trans"&gt;true&lt;/prop&gt;
              &lt;/props&gt;
          &lt;/property&gt;
  
          &lt;property name="jpaPropertyMap"&gt;
              &lt;map&gt;
                &lt;entry key="eclipselink.weaving" value="false"/&gt;
              &lt;/map&gt;
          &lt;/property&gt;
  
          &lt;property name="loadTimeWeaver"&gt;
              &lt;bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/&gt;
          &lt;/property&gt;
      &lt;/bean&gt;
  
      &lt;bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"&gt;
          &lt;property name="entityManagerFactory" ref="entityManagerFactory"/&gt;
      &lt;/bean&gt;
  
      &lt;tx:annotation-driven transaction-manager="transactionManager"/&gt;
  
      &lt;bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"&gt;
          &lt;property name="jndiName" value="java:comp/env/jdbc/social_networking"/&gt;
      &lt;/bean&gt;
  
      &lt;!--The bean shown in the beginning is configured here--&gt;
      &lt;bean id="authSuccessHandler" class="loginsuccesshandler.AuthSuccessHandler"/&gt; 
  
      &lt;bean id="testService" class="admin.dao.TestDAO"/&gt;
      &lt;bean id="stateService" class="admin.dao.StateDAO"/&gt;
      &lt;bean id="sharableService" class="admin.dao.SharableDAO"/&gt;
  &lt;/beans&gt;
  </code></pre>
  
  <hr>
  
  <p>The <code>web.xml</code> file.</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"&gt;        
  
      &lt;context-param&gt;
          &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
          &lt;param-value&gt;
              /WEB-INF/applicationContext.xml
              /WEB-INF/spring-security.xml
          &lt;/param-value&gt;
      &lt;/context-param&gt;
  
      &lt;context-param&gt;
          &lt;param-name&gt;javax.faces.PROJECT_STAGE&lt;/param-name&gt;
          &lt;!--&lt;param-value&gt;Development&lt;/param-value&gt;--&gt;
          &lt;param-value&gt;Production&lt;/param-value&gt;
      &lt;/context-param&gt;
  
      &lt;context-param&gt;
          &lt;param-name&gt;log4jConfigLocation&lt;/param-name&gt;
          &lt;param-value&gt;/WEB-INF/log4j.properties&lt;/param-value&gt;
      &lt;/context-param&gt;
  
      &lt;context-param&gt;
          &lt;param-name&gt;log4jExposeWebAppRoot&lt;/param-name&gt;
          &lt;param-value&gt;false&lt;/param-value&gt;
      &lt;/context-param&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;dispatcher&gt;REQUEST&lt;/dispatcher&gt;
          &lt;dispatcher&gt;FORWARD&lt;/dispatcher&gt;
      &lt;/filter-mapping&gt;
  
      &lt;listener&gt;
          &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
      &lt;/listener&gt;
  
      &lt;listener&gt;
          &lt;listener-class&gt;org.springframework.web.context.request.RequestContextListener&lt;/listener-class&gt;
      &lt;/listener&gt;        
  
      &lt;listener&gt;
          &lt;listener-class&gt;org.springframework.security.web.session.HttpSessionEventPublisher&lt;/listener-class&gt;
      &lt;/listener&gt;
  
      &lt;listener&gt;
          &lt;listener-class&gt;org.springframework.web.util.Log4jConfigListener&lt;/listener-class&gt;
      &lt;/listener&gt;
  
      &lt;servlet&gt;
          &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
          &lt;servlet-class&gt;javax.faces.webapp.FacesServlet&lt;/servlet-class&gt;
          &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
      &lt;/servlet&gt;
  
      &lt;servlet-mapping&gt;
          &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
          &lt;url-pattern&gt;*.jsf&lt;/url-pattern&gt;
      &lt;/servlet-mapping&gt;
  
      &lt;servlet-mapping&gt;
          &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
          &lt;url-pattern&gt;*.xhtml&lt;/url-pattern&gt;
      &lt;/servlet-mapping&gt;
  
      &lt;security-constraint&gt;
          &lt;display-name&gt;Restrict direct access to XHTML files&lt;/display-name&gt;
          &lt;web-resource-collection&gt;
              &lt;web-resource-name&gt;XHTML files&lt;/web-resource-name&gt;
              &lt;url-pattern&gt;*.xhtml&lt;/url-pattern&gt;
          &lt;/web-resource-collection&gt;
          &lt;auth-constraint /&gt;
      &lt;/security-constraint&gt; 
  
      &lt;session-config&gt;
          &lt;session-timeout&gt;
              120
          &lt;/session-timeout&gt;
      &lt;/session-config&gt;
      &lt;welcome-file-list&gt;
          &lt;welcome-file&gt;/utility/Login.jsf&lt;/welcome-file&gt;
      &lt;/welcome-file-list&gt;
  
      &lt;resource-ref&gt;
          &lt;res-ref-name&gt;jdbc/social_networking&lt;/res-ref-name&gt;
          &lt;res-type&gt;javax.sql.DataSource&lt;/res-type&gt;
          &lt;res-auth&gt;Container&lt;/res-auth&gt;
      &lt;/resource-ref&gt;
  &lt;/web-app&gt;
  </code></pre>
  
  <hr>
  
  <p>The debug information can be seen below, when an attempt is made to login which ultimately fails.</p>
  
  <pre><code>DEBUG [http-apr-8080-exec-55] (AntPathRequestMatcher.java:116) - Checking match of request : '/j_spring_security_check'; against '/utility/login.jsf*'
  DEBUG [http-apr-8080-exec-55] (AntPathRequestMatcher.java:116) - Checking match of request : '/j_spring_security_check'; against '/utility/login.jsf*'
  DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 1 of 13 in additional filter chain; firing Filter: 'ChannelProcessingFilter'
  DEBUG [http-apr-8080-exec-55] (AntPathRequestMatcher.java:116) - Checking match of request : '/j_spring_security_check'; against '/admin_side/**'
  DEBUG [http-apr-8080-exec-55] (AntPathRequestMatcher.java:116) - Checking match of request : '/j_spring_security_check'; against '/utility/login.jsf'
  DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
  DEBUG [http-apr-8080-exec-55] (HttpSessionSecurityContextRepository.java:139) - HttpSession returned null object for SPRING_SECURITY_CONTEXT
  DEBUG [http-apr-8080-exec-55] (HttpSessionSecurityContextRepository.java:85) - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@1103da5. A new one will be created.
  DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 3 of 13 in additional filter chain; firing Filter: 'ConcurrentSessionFilter'
  DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 4 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
  DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 5 of 13 in additional filter chain; firing Filter: 'LogoutFilter'
  DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 6 of 13 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
  DEBUG [http-apr-8080-exec-55] (AbstractAuthenticationProcessingFilter.java:189) - Request is to process authentication
  DEBUG [http-apr-8080-exec-55] (ProviderManager.java:152) - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
  DEBUG [http-apr-8080-exec-55] (JdbcTemplate.java:637) - Executing prepared SQL query
  DEBUG [http-apr-8080-exec-55] (JdbcTemplate.java:572) - Executing prepared SQL statement [select email_id, password, enabled from user_table where lower(email_id)=lower(?)]
  DEBUG [http-apr-8080-exec-55] (DataSourceUtils.java:110) - Fetching JDBC Connection from DataSource
  DEBUG [http-apr-8080-exec-55] (DataSourceUtils.java:327) - Returning JDBC Connection to DataSource
  DEBUG [http-apr-8080-exec-55] (JdbcTemplate.java:637) - Executing prepared SQL query
  DEBUG [http-apr-8080-exec-55] (JdbcTemplate.java:572) - Executing prepared SQL statement [select ut.email_id, ur.authority from user_table ut, user_roles ur where ut.user_id=ur.user_id and lower(ut.email_id)=lower(?)]
  DEBUG [http-apr-8080-exec-55] (DataSourceUtils.java:110) - Fetching JDBC Connection from DataSource
  DEBUG [http-apr-8080-exec-55] (DataSourceUtils.java:327) - Returning JDBC Connection to DataSource
  DEBUG [http-apr-8080-exec-55] (AbstractBeanFactory.java:246) - Returning cached instance of singleton bean 'authSuccessHandler'
  DEBUG [http-apr-8080-exec-55] (AbstractBeanFactory.java:246) - Returning cached instance of singleton bean 'org.springframework.security.core.session.SessionRegistryImpl#0'
  DEBUG [http-apr-8080-exec-55] (AbstractFallbackTransactionAttributeSource.java:106) - Adding transactional method 'rowCount' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
  DEBUG [http-apr-8080-exec-55] (DelegatingMethodSecurityMetadataSource.java:65) - Caching method [CacheKey[admin.dao.StateDAO; public abstract java.lang.Long admin.dao.service.StateService.rowCount()]] with attributes [ROLE_ADMIN]
  DEBUG [http-apr-8080-exec-55] (AbstractBeanFactory.java:246) - Returning cached instance of singleton bean 'transactionManager'
  DEBUG [http-apr-8080-exec-55] (AbstractPlatformTransactionManager.java:366) - Creating new transaction with name [admin.dao.StateDAO.rowCount]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
  DEBUG [http-apr-8080-exec-55] (JpaTransactionManager.java:369) - Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl@84ff11] for JPA transaction
  DEBUG [http-apr-8080-exec-55] (JpaTransactionManager.java:408) - Not exposing JPA transaction [org.hibernate.ejb.EntityManagerImpl@84ff11] as JDBC transaction because JpaDialect [org.springframework.orm.jpa.DefaultJpaDialect@d9dbb8] does not support JDBC Connection retrieval
  DEBUG [http-apr-8080-exec-55] (AbstractSecurityInterceptor.java:194) - Secure object: ReflectiveMethodInvocation: public abstract java.lang.Long admin.dao.service.StateService.rowCount(); target is of class [admin.dao.StateDAO]; Attributes: [ROLE_ADMIN]
  DEBUG [http-apr-8080-exec-55] (AbstractBeanFactory.java:246) - Returning cached instance of singleton bean 'authSuccessHandler'
  DEBUG [http-apr-8080-exec-55] (AbstractBeanFactory.java:246) - Returning cached instance of singleton bean 'org.springframework.security.core.session.SessionRegistryImpl#0'
  DEBUG [http-apr-8080-exec-55] (AbstractPlatformTransactionManager.java:844) - Initiating transaction rollback
  DEBUG [http-apr-8080-exec-55] (JpaTransactionManager.java:534) - Rolling back JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl@84ff11]
  DEBUG [http-apr-8080-exec-55] (JpaTransactionManager.java:594) - Closing JPA EntityManager [org.hibernate.ejb.EntityManagerImpl@84ff11] after transaction
  DEBUG [http-apr-8080-exec-55] (EntityManagerFactoryUtils.java:338) - Closing JPA EntityManager
  DEBUG [http-apr-8080-exec-55] (AbstractAuthenticationProcessingFilter.java:346) - Authentication request failed: org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
  DEBUG [http-apr-8080-exec-55] (AbstractAuthenticationProcessingFilter.java:347) - Updated SecurityContextHolder to contain null Authentication
  DEBUG [http-apr-8080-exec-55] (AbstractAuthenticationProcessingFilter.java:348) - Delegating to authentication failure handler loginsuccesshandler.AuthenticationFailureHandler@14883a3
  DEBUG [http-apr-8080-exec-55] (DefaultRedirectStrategy.java:36) - Redirecting to '/SocialNetworking/utility/Login.jsf'
  DEBUG [http-apr-8080-exec-55] (HttpSessionSecurityContextRepository.java:269) - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
  DEBUG [http-apr-8080-exec-55] (SecurityContextPersistenceFilter.java:97) - SecurityContextHolder now cleared, as request processing completed
  DEBUG [http-apr-8080-exec-49] (AntPathRequestMatcher.java:116) - Checking match of request : '/utility/login.jsf'; against '/utility/login.jsf*'
  DEBUG [http-apr-8080-exec-49] (AntPathRequestMatcher.java:116) - Checking match of request : '/utility/login.jsf'; against '/utility/login.jsf*'
  DEBUG [http-apr-8080-exec-49] (FilterChainProxy.java:180) - /utility/Login.jsf has an empty filter list
  </code></pre>
  
  <hr>
  
  <p>The last thing:</p>
  
  <p>When I give up this bean and unregister from the <code>application-context.xml</code> file, the login is made successfully but the following information can be seen on the server console.</p>
  
  <pre><code>DEBUG [http-apr-8080-exec-165] (HttpSessionSecurityContextRepository.java:139) - HttpSession returned null object for SPRING_SECURITY_CONTEXT
  DEBUG [http-apr-8080-exec-165] (HttpSessionSecurityContextRepository.java:85) - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@b910c1. A new one will be created.
  </code></pre>