SpringSecurity(八)session管理

限制用户最大登录数

SpringSecurityConfig
.and()
    .sessionManagement()
    .maximumSessions(1)
    .maxSessionsPreventsLogin(false) // 当达到maximumSessions时,true表示不能踢掉前面的登录,false表示踢掉前面的用户
    .expiredSessionStrategy(new LzcExpiredSessionStrategy()) // 当达到maximumSessions时,踢掉前面登录用户后的操作
LzcExpiredSessionStrategy
public class LzcExpiredSessionStrategy implements SessionInformationExpiredStrategy {
    private ObjectMapper objectMapper = new ObjectMapper();
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
        // 这里也可以根据需要返回html页面或者json数据
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "已经另一台机器登录,您被迫下线。" + event.getSessionInformation().getLastRequest());
        event.getResponse().setContentType("application/json;charset=UTF-8");
        event.getResponse().getWriter().write(objectMapper.writeValueAsString(map));

        // 如果是跳转html页面,url代表跳转的地址
        // redirectStrategy.sendRedirect(event.getRequest(), event.getResponse(), "url");
    }
}

分布式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.port=6379
spring.redis.host=127.0.0.1
spring.session.store-type=redis

代码地址   https://github.com/923226145/SpringSecurity/tree/master/chapter8

猜你喜欢

转载自blog.csdn.net/lizc_lizc/article/details/84135106