Session:在计算机中,尤为是在网络应用中,称为“会话控制”。Session 对象存储特定用户会话所需的属性及配置信息。这样,当用户在应用程序的 Web 页之间跳转时,存储在 Session 对象中的变量将不会丢失,而是在整个用户会话中一直存在下去。当用户请求来自应用程序的 Web 页时,若是该用户尚未会话,则 Web 服务器将自动建立一个 Session 对象。当会话过时或被放弃后,服务器将终止该会话。Session 对象最多见的一个用法就是存储用户的首选项。java
本文主要描述在 Spring Security
下 Session
的如下三种管理,git
Session
超时时间Session
的并发策略Session
处理application.yml
配置超时时间server:
port: 80
session:
timeout: 60
复制代码
http.
......
.sessionManagement()
.invalidSessionUrl("/session/invalid")//session失效跳转的连接
.....
复制代码
Cotroller
中/session/invalid
@GetMapping("/session/invalid")
@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
public Result<String> sessionInvalid() {
return ResultUtil.error(HttpStatus.UNAUTHORIZED.value(), "session失效");
}
复制代码
http.
......
.maximumSessions(1)//最大session并发数量1
.maxSessionsPreventsLogin(false)//false以后登陆踢掉以前登陆,true则不容许以后登陆
.expiredSessionStrategy(new MerryyounExpiredSessionStrategy())//登陆被踢掉时的自定义操做
.....
复制代码
MerryyounExpiredSessionStrategy
@Slf4j
public class MerryyounExpiredSessionStrategy implements SessionInformationExpiredStrategy {
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent eventØ) throws IOException, ServletException {
eventØ.getResponse().setContentType("application/json;charset=UTF-8");
eventØ.getResponse().getWriter().write("并发登陆!");
}
}
复制代码
当maxSessionsPreventsLogin(true)
可参考:Spring-Security和security-oauth2spring
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>1.3.1.RELEASE</version>
</dependency>
复制代码
spring:
redis:
host: localhost
port: 6379
session:
store-type: redis
复制代码
8080
和8081
端口分别启动项目java -jar spring-security.jar --server.port=8080
java -jar spring-security.jar --server.port=8081
复制代码
效果以下:json
关于更多Spring Session可参考:程序猿DD服务器
从个人 github 中下载,github.com/longfeizhen…网络