Question

How do you setup spring-security for a restful api using a cookie based authentication?

Currently I'm trying to make sure a request has a cookie with a sessionId on it that I validate against redis.

I've tried joining these two examples together:

http://sleeplessinslc.blogspot.com/2012/02/spring-security-stateless-cookie-based.html

https://spring.io/guides/tutorials/rest/5/

By combining the two I'm essentially implementing the cookie filter, Authentication, and SecurityContext and then wiring up the filter like this.

@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<Filter> getFilters() {
            List<Filter> filters = new ArrayList<Filter>();
            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;
}

}

Was it helpful?

Solution

The solution actually works, just had to disable the defaults of WebSecurityConfigurerAdapter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top