【问题标题】:Limit sessions in spring boot with redis使用 redis 限制 Spring Boot 中的会话
【发布时间】:2017-05-23 13:00:43
【问题描述】:

我正在使用带有 Redis 的 Spring Boot 来验证用户身份。

我的应用程序首次使用用户名和密码对用户进行身份验证,并发送回一个唯一令牌。对于进一步的交易,用户在标头中发送令牌。

这很好用,但是当用户已经通过身份验证并且在 Redis 中有一个令牌时,我不希望 spring 创建一个新令牌。

设置:Spring Boot:1.4.0; Java 1.8

我确实尝试了以下方法,但它不起作用。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter 
{   
  @Autowired
  private CustomAuthenticationProvider authProvider;

  @Bean
  public HttpSessionStrategy httpSessionStrategy() 
  {
     return new HeaderHttpSessionStrategy();
  }

   @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception 
  {
     auth.authenticationProvider(authProvider);
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception 
  {
    http
        .authorizeRequests()
        .anyRequest().authenticated()                       
        .and()
        .requestCache()
        .requestCache(new NullRequestCache())
        .and()
        .httpBasic()
        .and()
        .sessionManagement()
        .maximumSessions(1)
        .maxSessionsPreventsLogin(true)
        .sessionRegistry(sessionRegistry());
  }


  @Bean
  public SessionRegistry sessionRegistry() 
  {
     SessionRegistry sessionRegistry = new SessionRegistryImpl();
     return sessionRegistry;
  }

  @Bean
  public static HttpSessionEventPublisher httpSessionEventPublisher() 
  {
     return new HttpSessionEventPublisher();
  }   
}

【问题讨论】:

  • 您要将现有的有效令牌返回给该用户还是拒绝登录?
  • @amantsingh 返回现有令牌。我都想知道。
  • 请分享自定义身份验证处理程序的代码以及您在 Redis 中设置令牌的部分。

标签: java spring spring-boot spring-security


【解决方案1】:
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Autowired
        FindByIndexNameSessionRepository<ExpiringSession> sessionRepository;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
                http
                        // other config goes here...
                        .sessionManagement()
                                .maximumSessions(1)
                                .sessionRegistry(sessionRegistry());
        }

        @Bean
        SpringSessionBackedSessionRegistry sessionRegistry() {
                return new SpringSessionBackedSessionRegistry(this.sessionRepository);
        }
}

更多详情见here

【讨论】:

  • 我也试过这个,但没有奏效。这可能适用于 oob 春季会议。您能否确认这是否也适用于 Redis 的春季?每次我发送相同的用户名和密码时,它都会返回新的令牌并接受所有令牌。
  • 那么为什么你使用HeaderHttpSessionStrategy
猜你喜欢
  • 2022-10-13
  • 2015-05-07
  • 2015-12-23
  • 2018-12-16
  • 2018-10-21
  • 2018-04-07
  • 2017-08-22
  • 1970-01-01
  • 2019-08-08
相关资源
最近更新 更多