单点登出
[!quote] 单点登出 单点登出 就是当一个用户在多个地方进行登录时,应用可能会需要让先前的会话失效
- 自定义 MySessionInformationExpiredStrategy 实现 SessionInformationExpiredStrategy 接口
java
package com.example.spring_security.infrastructure.config;
public class MySessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {
Logger logger = LoggerFactory.getLogger(MySessionInformationExpiredStrategy.class);
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
logger.atInfo().log("会话过期了,我要做一些处理");
Result<Object> responseResult = Result.buildResult(Result.Status.ERROR, "会话过期");
ObjectMapper objectMapper = new ObjectMapper();
String jsonData = objectMapper.writeValueAsString(responseResult);
HttpServletResponse response = event.getResponse();
response.setContentType("application/json;charset=utf-8");
response.getWriter().println(jsonData);
}
}- 在 Security 配置文件
SecurityConfig中配置
java
http.sessionManagement(sessionManagement -> {
sessionManagement
// 一个账号最多在一个地方登录
.maximumSessions(1)
// 如果会话过期了,会调用MySessionInformationExpiredStrategy
.expiredSessionStrategy(new MySessionInformationExpiredStrategy());
});