1. 设置session的过期时间
server:
servlet:
session:
timeout: 60
2.设置基于session的单点登录,超时后登录的网址,超时后的登录状态,
http.sessionManagement().invalidSessionUrl("/invalid").maximumSessions(1).maxSessionsPreventsLogin(false).expiredSessionStrategy(new CustomExpiredSessionStrategy());
CustomExpiredSessionStrategy
package com.hanhuide.core.handler;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hanhuide.core.model.CustomResponseBody;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class CustomExpiredSessionStrategy implements SessionInformationExpiredStrategy {
private ObjectMapper objectMapper = new ObjectMapper();
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
event.getResponse().setContentType("application/json;charset=UTF-8");
// CustomResponseBody body = new CustomResponseBody();
// body.setStatus(0000);
// body.setMsg("您已在其他地方登录,请检查,时间为{" + event.getSessionInformation().getLastRequest() + "}");
// event.getResponse().getWriter().write(JSON.toJSONString(body));
redirectStrategy.sendRedirect(event.getRequest(), event.getResponse(), "/login");
}
}
3.
package com.hanhuide.core.controller;
import com.hanhuide.core.mapper.CeshiMapper;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.hanhuide.core.model.SysUser;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import java.util.List;
/**
* @program: maven
* @description:
* @author: 韩惠德
* @create: 2019-12-24 16:41
* @version: 1.0
**/
@RestController
@Slf4j
public class Contrller11 {
@Resource
private CeshiMapper ceshiMapper;
@ApiOperation(value = "测试数据源", notes = "测试数据源")
@GetMapping("system")
public List<SysUser> ceshi() {
return ceshiMapper.findAll();
}
@ApiOperation(value = "测试数据源2", notes = "测试数据源2")
@GetMapping("/system/menu")
public List<SysUser> ceshi2() {
return ceshiMapper.findAll2();
}
@RequestMapping("/invalid")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String invalid() {
return "Session 已过期,请重新登录";
}
}
刷新火狐浏览器 直接跳转到登录页面