【问题标题】:How to maintain user session in clustered environment using spring security如何使用 Spring Security 在集群环境中维护用户会话
【发布时间】:2020-10-26 16:22:00
【问题描述】:

我们有一个登录页面,并在 SecurityConfig 中配置了 CustomAuthenticationProvider,在此类中将凭据存储在 UsernamePasswordAuthenticationToken 对象中。我们在 Rest Controller 中捕获用户凭据。我们已经在集群环境中部署了应用程序。

如果我们使用凭据登录,请求将发送到一个服务器,并且用户详细信息将进入 Rest Controller,如果我们刷新页面,则在同一个会话中,请求将发送到另一台服务器,因此我们得到空用户详细信息。

@GetMapping("/myRentals")
    public  ModelAndView myDetails(@AuthenticationPrincipal UserDetails user) {
        logger.info("user:"+user);
}


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private CustomAuthenticationProvider customAuthProvider;




    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(customAuthProvider);
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {


        http.csrf().disable().authorizeRequests()
                .antMatchers("/")
                .permitAll()
                .and()
                .formLogin()
                .loginPage("/")
                .loginProcessingUrl("/authenticateTheUser")
                .permitAll()
                .and()
                .logout().permitAll()
                .and()
                .exceptionHandling().accessDeniedPage("/access-denied");

    }

}

【问题讨论】:

    标签: spring-mvc spring-security


    【解决方案1】:
    • 实施粘性会话
    • 查看Spring Session,其中可以由JDBCmongoRedis 支持Http 会话,这使得支持集群会话变得微不足道。 Spring的安全SecurityContextPersistenceFilter会自动使用它

    参考

    https://docs.spring.io/spring-session/docs/current/reference/html5/guides/boot-jdbc.html

    Spring Session 提供了一个 API 和实现来管理用户的会话信息,同时还可以轻松支持集群会话,而无需绑定到特定于应用程序容器的解决方案

    我们没有使用 Tomcat 的 HttpSession,而是将值保存在 H2 数据库中。 Spring Session 将 HttpSession 替换为由关系数据库支持的实现。当 Spring Security 的 SecurityContextPersistenceFilter 将 SecurityContext 保存到 HttpSession 时,会被持久化到 H2 数据库中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-09
      • 1970-01-01
      • 2013-11-27
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      • 2019-09-22
      相关资源
      最近更新 更多