Spring Security会话共享

前面所讲的会话管理都是单机上的会话管理,如果当前是集群环境,前面所讲的会话管理方案就会失效。此时可以利用 spring-session 结合 redis 实现 session 共享。

实战

引入依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.session</groupId>
  <artifactId>spring-session-data-redis</artifactId>
</dependency>

编写配置

spring.redis.host=localhost
spring.redis.port=6379

配置Security

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.security.SpringSessionBackedSessionRegistry;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    private final FindByIndexNameSessionRepository sessionRepository;


    @Autowired
    public SecurityConfig(FindByIndexNameSessionRepository sessionRepository) {
        this.sessionRepository = sessionRepository;
    }

    @Bean
    public UserDetailsService userDetailsService() {
        ....
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .rememberMe()
                .and()
                .csrf().disable()
                .sessionManagement()  //开启会话管理
                .maximumSessions(1)  //允许同一个用户只允许创建一个会话*/
                .expiredUrl("/login")//会话过期处理  传统 web 开发
                .expiredSessionStrategy(event -> {
                    HttpServletResponse response = event.getResponse();
                    response.setContentType("application/json;charset=UTF-8");
                    Map<String, Object> result = new HashMap<>();
                    result.put("status", 500);
                    result.put("msg", "当前会话已经失效,请重新登录!");
                    String s = new ObjectMapper().writeValueAsString(result);
                    response.getWriter().println(s);
                    response.flushBuffer();
                }).sessionRegistry(sessionRegistry());//前后端分离开发处理
        //.maxSessionsPreventsLogin(true);//登录之后禁止再次登录*/
    }

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

}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security中实现Session共享有多种方式,可以使用分布式缓存、数据库存储或使用单点登录(Single Sign-On)等方式。下面我将介绍一种常见的方法,即使用分布式缓存实现Session共享。 一、配置分布式缓存 1. 首先,您需要选择一个适合您的分布式缓存解决方案,比如Redis或Memcached。 2. 根据您选择的分布式缓存,添加相应的依赖到项目中,并配置缓存服务器的连接信息。 二、配置Spring Security 1. 创建一个自定义的SessionRegistry实现类,用于管理会话信息。该类可以使用缓存来存储和获取会话数据。您可以实现SessionRegistry接口,并使用分布式缓存来实现相关的方法。 2. 在Spring Security的配置类中添加以下代码: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private SessionRegistry sessionRegistry; @Override protected void configure(HttpSecurity http) throws Exception { http .sessionManagement() .maximumSessions(-1) .sessionRegistry(sessionRegistry) .and() .invalidSessionUrl("/login?expired") .and() // 其他的安全配置... } @Bean public HttpSessionEventPublisher httpSessionEventPublisher() { return new HttpSessionEventPublisher(); } } ``` 三、配置会话管理器 1. 创建一个自定义的会话管理器,并注入SessionRegistry实例。 例如,可以创建一个名为CustomConcurrentSessionControlStrategy的类,并实现ConcurrentSessionControlStrategy接口: ```java @Component public class CustomConcurrentSessionControlStrategy extends ConcurrentSessionControlStrategy { public CustomConcurrentSessionControlStrategy(SessionRegistry sessionRegistry) { super(sessionRegistry); } } ``` 2. 在Spring Security的配置类中添加以下代码: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private SessionRegistry sessionRegistry; @Autowired private CustomConcurrentSessionControlStrategy customConcurrentSessionControlStrategy; @Override protected void configure(HttpSecurity http) throws Exception { http .sessionManagement() .maximumSessions(-1) .sessionRegistry(sessionRegistry) .sessionAuthenticationErrorUrl("/login?expired") .and() .invalidSessionUrl("/login?expired") .and() // 其他的安全配置... } @Bean public HttpSessionEventPublisher httpSessionEventPublisher() { return new HttpSessionEventPublisher(); } @Bean public SessionRegistry sessionRegistry() { return new SessionRegistryImpl(); } @Bean public CustomConcurrentSessionControlStrategy customConcurrentSessionControlStrategy(SessionRegistry sessionRegistry) { return new CustomConcurrentSessionControlStrategy(sessionRegistry); } } ``` 通过以上配置,您可以启用会话共享并使用分布式缓存来存储和管理会话信息。请根据您的需求进行相应的调整和修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值