title: Spring Security: Access the current authenticated User inside a servlet Filter
body: <p>I recently started learning about Spring Security and today I stepped on this basic (I believe) question: Why can't I access the current Principal inside a Servlet Filter as demonstrated in the class below:</p>
  
  <pre><code>package com.acme.test;
  
  import java.io.IOException;
  
  import javax.servlet.Filter;
  import javax.servlet.FilterChain;
  import javax.servlet.FilterConfig;
  import javax.servlet.ServletException;
  import javax.servlet.ServletRequest;
  import javax.servlet.ServletResponse;
  
  import org.springframework.security.core.Authentication;
  import org.springframework.security.core.context.SecurityContext;
  import org.springframework.security.core.context.SecurityContextHolder;
  import org.springframework.stereotype.Component;
  
  @Component
  public class TestFilter implements Filter {
  
      /*
       * (non-Javadoc)
       * 
       * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
       */
      @Override
      public void init(FilterConfig filterConfig) throws ServletException {
          // TODO Auto-generated method stub
  
      }
  
      /*
       * (non-Javadoc)
       * 
       * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
       * javax.servlet.ServletResponse, javax.servlet.FilterChain)
       */
      @Override
      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
              throws IOException, ServletException {
  
          SecurityContext securityContext = SecurityContextHolder.getContext();
          Authentication auth = securityContext.getAuthentication();
  
          // auth is null here
  
          chain.doFilter(request, response);
      }
  
      /*
       * (non-Javadoc)
       * 
       * @see javax.servlet.Filter#destroy()
       */
      @Override
      public void destroy() {
          // TODO Auto-generated method stub
  
      }
  
  }
  </code></pre>
  
  <p>The Authentication object retrieved with <em>Authentication auth = securityContext.getAuthentication();</em> is null. While using the above snippet inside an MVC @Controller works just fine (as expected).</p>
  
  <p>Why is this happening?</p>