2536-springsecurity Series--About session Management 1

Source: Internet
Author: User
Tags assert session id

Version information
<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>

Basic session Management in SS

    • Session Invalid Handling
    • Session Expiration Processing
    • Concurrent login Processing
    • Restrict duplicate logins and top numbers for the same user
    // 配置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);    }
Concurrent login Processing

For example, a user who logs on two computers and works on two computers can set a maximumsessions value of 2 so that springsecurity will maintain two valid sessions for the user when managing the session.

Restrict duplicate logins and top numbers for the same user

For example, a user is required to log on at most one computer, and another computer logs on with the previous login information.
Maximumsessions set to 1
Maxsessionspreventslogin set to False

For example, require a user to log on at most one computer, and another computer login will prompt for non-recurring logins.
Maximumsessions set to 1
Maxsessionspreventslogin set to True

Session invalidation processing and session expiration processing

Simple processing, just URL jump, configuration invalidsessionurl and expiredurl two parameters can be.
If you need to record user information, logs, etc. when the session is invalid or expired, you need to customize the implementation class Invalidsessionstrategy and Sessioninformationexpiredstrategy

Custom processing

自定义三个类AbstractSessionStrategyCustomExpiredSessionStrategyCustomInvalidSessionStrategy

Configuring in the Config class

    /**     * 配置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);    }

The code for the three implementation classes:

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 ());    /** * The URL of the jump */private String destinationurl;    /** * REDIRECT Strategy */private Redirectstrategy redirectstrategy = new Defaultredirectstrategy ();    /** * Whether to create a new session before jumping */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 expires, jump to" + TargetUrl);        Redirectstrategy.sendredirect (Request, response, TargetUrl);            } else {String message = "Session has expired, please login again"; if (Isconcurrency ()) {message = message + ", it is possibleIs the result of concurrent logins ";            } 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 invalidation is caused by concurrent */protected Boolean isconcurrency () {return false; }/** * Determines whether a new session should be created before redirecting (to * avoid possible looping issu ES 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);    }}
Complete Project Engineering Reference

Https://github.com/starmoon1994/springsecurity-collection

2536-springsecurity Series--About session Management 1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.