標籤:vax authorize str for epo rop .data 資訊 rom
版本資訊
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.14.RELEASE</version> <relativePath/> <!-- lookup parent from repository --></parent><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> <version>1.5.14.RELEASE</version> <!--實際裡面spring-security-web的版本是4.2.7--></dependency>
在ss中基本的session管理
- session無效處理
- session到期處理
- 並發登入處理
- 限制同一使用者重複登入和頂號
// 配置session相關 // CustomSecurityProperties是自訂的常量參數類 private void configSession(HttpSecurity http) throws Exception { http.sessionManagement() .invalidSessionStrategy(invalidSessionStrategy) //session無效處理策略 .invalidSessionUrl(CustomSecurityProperties.invalidSessionUrl) .maximumSessions(1) //同一使用者最大session數 .maxSessionsPreventsLogin(false) //達到最大數禁止登入(預防並發登入) .expiredSessionStrategy(sessionInformationExpiredStrategy) //session到期處理策略 .expiredUrl(CustomSecurityProperties.expiredSessionUrl); }
並發登入處理
例如使用者在兩台電腦上登入,並在兩台電腦上辦公,可設定maximumSessions值為2,這樣springsecurity在管理session時會對該使用者保持兩個有效session。
限制同一使用者重複登入和頂號
例如要求使用者最多隻能在一台電腦上登入,並且另一台電腦登入會頂掉之前的登入資訊。
maximumSessions設定為1
maxSessionsPreventsLogin設定為false
例如要求使用者最多隻能在一台電腦上登入,並且另一台電腦登入會提示不可重複登入。
maximumSessions設定為1
maxSessionsPreventsLogin設定為true
session無效處理和session到期處理
簡單的處理,只是進行url跳轉,配置invalidSessionUrl和expiredUrl兩個參數即可。
如果需要記錄session無效或到期時的使用者資訊、日誌等,需要自訂實作類別InvalidSessionStrategy和SessionInformationExpiredStrategy
自訂處理
自訂三個類AbstractSessionStrategyCustomExpiredSessionStrategyCustomInvalidSessionStrategy
在config類中進行配置
/** * 配置sec的session失效策略 * 配置給sessionManagement */ @Bean @ConditionalOnMissingBean(InvalidSessionStrategy.class) public InvalidSessionStrategy invalidSessionStrategy() { return new CustomInvalidSessionStrategy(CustomSecurityProperties.invalidSessionUrl); } /** * 配置sec的session到期策略 * 配置給sessionManagement */ @Bean @ConditionalOnMissingBean(SessionInformationExpiredStrategy.class) public SessionInformationExpiredStrategy sessionInformationExpiredStrategy() { return new CustomExpiredSessionStrategy(CustomSecurityProperties.invalidSessionUrl); }
三個實作類別的代碼:
AbstractSessionStrategy
import com.company.testss12.support.RetVO;import com.fasterxml.jackson.databind.ObjectMapper;import org.apache.commons.lang3.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.http.HttpStatus;import org.springframework.security.web.DefaultRedirectStrategy;import org.springframework.security.web.RedirectStrategy;import org.springframework.security.web.util.UrlUtils;import org.springframework.util.Assert;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;/** * @author starmoon1994 */public class AbstractSessionStrategy { private final Logger logger = LoggerFactory.getLogger(getClass()); /** * 跳轉的url */ private String destinationUrl; /** * 重新導向策略 */ private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); /** * 跳轉前是否建立新的session */ private boolean createNewSession = true; private ObjectMapper objectMapper = new ObjectMapper(); /** */ public AbstractSessionStrategy(String invalidSessionUrl) { Assert.isTrue(UrlUtils.isValidRedirectUrl(invalidSessionUrl), "url must start with ‘/‘ or with ‘http(s)‘"); this.destinationUrl = invalidSessionUrl; } protected void onSessionInvalid(HttpServletRequest request, HttpServletResponse response) throws IOException { logger.info("onSessionInvalid IP:{} URI:{}", request.getRemoteHost(), request.getRequestURI()); if (createNewSession) { request.getSession(); } String sourceUrl = request.getRequestURI(); String targetUrl; if (StringUtils.endsWithIgnoreCase(sourceUrl, ".html")) { targetUrl = destinationUrl;//+".html"; logger.info("session失效,跳轉到" + targetUrl); redirectStrategy.sendRedirect(request, response, targetUrl); } else { String message = "session已失效,請重新登入"; if (isConcurrency()) { message = message + ",有可能是並發登入導致的"; } response.setStatus(HttpStatus.UNAUTHORIZED.value()); response.setContentType("application/json;charset=UTF-8"); RetVO retVO = new RetVO(); retVO.setMsg(message); response.getWriter().write(objectMapper.writeValueAsString(retVO)); } } /** * session失效是否是並發導致的 */ protected boolean isConcurrency() { return false; } /** * Determines whether a new session should be created before redirecting (to * avoid possible looping issues where the same session ID is sent with the * redirected request). Alternatively, ensure that the configured URL does * not pass through the {@code SessionManagementFilter}. * * @param createNewSession defaults to {@code true}. */ public void setCreateNewSession(boolean createNewSession) { this.createNewSession = createNewSession; }}
CustomExpiredSessionStrategy
import org.springframework.security.web.session.SessionInformationExpiredEvent;import org.springframework.security.web.session.SessionInformationExpiredStrategy;import java.io.IOException;/** * session失效策略 */public class CustomExpiredSessionStrategy extends AbstractSessionStrategy implements SessionInformationExpiredStrategy { public CustomExpiredSessionStrategy(String invalidSessionUrl) { super(invalidSessionUrl); } @Override public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException { onSessionInvalid(event.getRequest(), event.getResponse()); } @Override protected boolean isConcurrency() { return true; }}
CustomInvalidSessionStrategy
import org.springframework.security.web.session.InvalidSessionStrategy;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;/** * @author starmoon1994 */public class CustomInvalidSessionStrategy extends AbstractSessionStrategy implements InvalidSessionStrategy { public CustomInvalidSessionStrategy(String invalidSessionUrl) { super(invalidSessionUrl); } @Override public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException { onSessionInvalid(request, response); }}
完整項目工程參考
https://github.com/starmoon1994/springsecurity-collection
2536-springsecurity系列--關於session管理1