title: Cookie based authentication using Spring Security and Redis for a RESTFul api with a Java Configuration
body: <p>How do you setup spring-security for a restful api using a cookie based authentication?</p>
  
  <p>Currently I'm trying to make sure a request has a cookie with a sessionId on it that I validate against redis.</p>
  
  <p>I've tried joining these two examples together:</p>
  
  <p><a href="http://sleeplessinslc.blogspot.com/2012/02/spring-security-stateless-cookie-based.html" rel="nofollow">http://sleeplessinslc.blogspot.com/2012/02/spring-security-stateless-cookie-based.html</a></p>
  
  <p><a href="https://spring.io/guides/tutorials/rest/5/" rel="nofollow">https://spring.io/guides/tutorials/rest/5/</a></p>
  
  <p>By combining the two I'm essentially implementing the cookie filter, Authentication, and SecurityContext and then wiring up the filter like this.</p>
  
  <pre><code>@Configuration
  @EnableWebSecurity
  public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  //have to use Autowired here, no other way to reference Bean
  
  
  @Override
  protected void configure(HttpSecurity http) throws Exception {
                 http.addFilter(cookieAuthenticationFilter()).authorizeRequests().antMatchers("*/**").hasAnyAuthority("ALLOW");
  }
  
  /**
   * The FilterProxyChain with the set of filters to apply.
   * 
   * @return The FilterProxyChain
   */
  @Bean(name = "springSecurityFilterChain")
    public FilterChainProxy getFilterChainProxy() {
        SecurityFilterChain chain = new SecurityFilterChain() {
  
            @Override
            public boolean matches(HttpServletRequest request) {
              // All goes through here
              return true;
            }
  
            @Override
            public List&lt;Filter&gt; getFilters() {
              List&lt;Filter&gt; filters = new ArrayList&lt;Filter&gt;();
              filters.add(cookieAuthenticationFilter());
              return filters;
           }            
        };
        return new FilterChainProxy(chain);
  }
  
  @Bean
    public CookieAuthenticationFilter cookieAuthenticationFilter() {
      return new CookieAuthenticationFilter(redisTemplate());
    }
  
  @Bean
  public JedisConnectionFactory redisConnectionFactory(){
      JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
      jedisConnectionFactory.setUsePool(true);
      jedisConnectionFactory.setHostName("localhost");//TODO: CHANGE TO CONFIG
      return jedisConnectionFactory;
  }
  
  @Bean
  public RedisTemplate redisTemplate(){
      RedisTemplate redisTemplate = new RedisTemplate();
      redisTemplate.setConnectionFactory(redisConnectionFactory());
      return redisTemplate;
  }
  </code></pre>
  
  <p>}</p>