使用Spring Security和Redis进行基于Cookie的身份验证,用于带有Java配置的RESTFul api

时间:2014-04-11 18:53:49

标签: java spring spring-mvc spring-security spring-data

如何使用基于cookie的身份验证为restful api设置spring-security?

目前我正在尝试确保请求中包含一个带有sessionId的cookie,我将对redis进行验证。

我尝试将这两个例子加在一起:

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

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

通过组合这两个我基本上实现了cookie过滤器,Authentication和SecurityContext,然后像这样连接过滤器。

@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;
}

}

1 个答案:

答案 0 :(得分:1)

解决方案确实有效,只需禁用WebSecurityConfigurerAdapter的默认值。