编程知识 cdmana.com

Spring security-3. Multi terminal login with same account forced to offline

SpringSecurity-3. The basic chapter Multiple login with the same account is forced to offline

maximumSession  Set to 1 , The same session Maximum number of login clients .

expiredSessionsStrategy:  Customize Session Timeout strategy

Two 、 example :

1.     Create custom policy class :

com.zhl.springsecuritydemo.config.CustomExpiredSessionStrategy

public class CustomExpiredSessionStrategy implements SessionInformationExpiredStrategy {

    private RedirectStrategy redirectStrategy=new DefaultRedirectStrategy();

    private ObjectMapper objectMapper=new ObjectMapper();
    /*
    *  When Session Post failure processing strategy 
    * */
    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
        /*1.   Jump to   Specify page .
        * */
       // redirectStrategy.sendRedirect(event.getRequest(),event.getResponse(),"/invalid");
        /*2.  return  json */

        Map<String,Object> map=new HashMap<>();
        map.put("code",403);
        map.put("msg"," Your login has timed out or you have logged in on another machine , You are forced to be offline ."
                +event.getSessionInformation().getLastRequest());

        String json = objectMapper.writeValueAsString(map);
        event.getResponse().setContentType("application/json;charset=utf-8");
        event.getResponse().getWriter().write(json);
    }
}

2.  To configure

To configure Session Protect 、 Failure policies are specified as custom policies .

               /*session Create policy configuration for  */
        .and().sessionManagement().
               sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
               .sessionFixation().migrateSession()
               .maximumSessions(1).maxSessionsPreventsLogin(false)
                .expiredSessionStrategy(new CustomExpiredSessionStrategy())

 

effect : Post login users have no impact , The account that logs in first is kicked offline .

 

 

版权声明
本文为[Zhang Hongliang]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224225141628W.html

Scroll to Top