SpringSecurity --会话过期策略(我们的爱情是有保质期的)
程序员文章站
2024-03-19 14:44:22
...
package com.zcw.demospringsecurity.demo9;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.session.InvalidSessionStrategy;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @ClassName : MyInvalidSessionStrategy
* @Description : SpringSecurity配置会话过期策略
* @Author : Zhaocunwei
* @Date: 2020-04-12 08:22
*/
public class MyInvalidSessionStrategy implements InvalidSessionStrategy {
@Override
public void onInvalidSessionDetected(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse)
throws IOException, ServletException {
httpServletResponse.setContentType("application/json;charset=utf-8");
httpServletResponse.getWriter().write("session无效");
}
}
package com.zcw.demospringsecurity.demo9;
import com.zcw.demospringsecurity.demo4.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* @ClassName : WebSecurityConfig
* @Description : 添加过期策略配置
* @Author : Zhaocunwei
* @Date: 2020-04-12 08:26
*/
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyUserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http)throws Exception{
http.authorizeRequests()
.antMatchers("/admin/**")
.hasRole("ADMIN")
.antMatchers("/user/**")
.hasRole("USER")
.antMatchers("/api/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.csrf()
.disable()
.formLogin()
.and()
.rememberMe()
.userDetailsService(userDetailsService)
.key("zcw")
.and()
.sessionManagement()
//配置session失效策略---默认情况下为30分钟失效
.invalidSessionStrategy(new MyInvalidSessionStrategy());
}
}