SpringSecurity 同账号多端登陆踢下线
限制最大登陆用户数量
- true表示已经登陆就不允许再次登陆
- false表示允许再次登陆但是之前的登陆账号会被踢下线
自定义处理策略类CustomExpiredSessionStrategy
- 页面跳转的方式
public class CustomExpiredSessionStrategy implements SessionInformationExpiredStrategy {
//页面跳转的方式
//页面跳转的处理逻辑
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent event)
throws IOException, ServletException {
redirectStrategy.sendRedirect(event.getRequest(), event.getResponse(), "踢下线后跳转的路径");
}
}
- 前后端分离返回JSON的方式
public class CustomExpiredSessionStrategy implements SessionInformationExpiredStrategy {
//前后端分离返回JSON的方式
//jackson的JSON处理对象
private ObjectMapper objectMapper = new ObjectMapper();
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent event)
throws IOException, ServletException {
Map<String, Object> map = new HashMap<>();
map.put("code", 403);
map.put("msg", "您的登陆已经超时或者已经在另一台机器登陆,您被迫下线!"
+ event.getSessionInformation().getLastRequest());
String json = objectMapper.writeValueAsString(map);
event.getResponse().setContentType("application/json;charset=utf-8");
event.getResponse().getWriter().write(json);
}
}
测试:
用谷歌浏览器登陆
再用火狐浏览器进行登陆,发现谷歌浏览器被题下线。