Spring Security with Custom Session Timeout

I need to set the session timeout from the GUI. Currently, we can change the session timeout around the world using the configuration

server.session.timeout=120
server.session.cookie.max-age=120
server.session.timeout=120`

We can also set a session timeout for each session.

session.setMaxInactiveInterval(120);

But no way was found to set the global session timeout during the flight. Is there any way to do this using spring boot

Thanks in advance

+4
source share
3 answers

I think you might need to use a spring jdbc or redis session so that you can have full control over the session store.

Spring boot jdbc session gives bean

@Autowired JdbcOperationsSessionRepository sessionRepository;

- .

@EnableJdbcHttpSession .

http://docs.spring.io/spring-session/docs/current/reference/html5/guides/httpsession-jdbc-boot.html#httpsession-jdbc-boot-sample

, , .

/springframework//JDBC/ -. * SQL

http://docs.spring.io/spring-session/docs/current/api/org/springframework/session/jdbc/JdbcOperationsSessionRepository.html

: 1

jdbc- , , . , - - , .

session.setMaxInactiveInterval(120);
+2

:

  • .
  • ajax ping , , 30 .
  • - , ping.
  • , .

http- :

    public static void customLogout(HttpServletRequest request, HttpServletResponse response){

        CookieClearingLogoutHandler cookieClearingLogoutHandler = new CookieClearingLogoutHandler(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);

        SecurityContextLogoutHandler securityContextLogoutHandler = new SecurityContextLogoutHandler();

        cookieClearingLogoutHandler.logout(request, response, null);

        securityContextLogoutHandler.logout(request, response, null);

    }
0

:

  • cron 5 ( ), (.. , ) , .
  • () Faye, UI ( Faye), .

You can use something like this to expire the token:

public void expireToken (HttpServletRequest request, HttpServletResponse response){
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null){    
        SecurityContextHolder.getContext().setAuthentication(null);
    }
}

To get all current sessions, you can use the following:

public class UserController {
    @Autowired
    private SessionRegistry sessionRegistry;

    public void listLoggedInUsers() {
        final List<Object> allPrincipals = sessionRegistry.getAllPrincipals();

        for(final Object principal : allPrincipals) {
            if(principal instanceof SecurityUser) {
                final SecurityUser user = (SecurityUser) principal;

                // if currentTime > logInTime + threshold time
                expireToken();
            }
        }
    }
}

Note. I personally avoid polling the backend from the interface, as it does not seem optimal.

-1
source

Source: https://habr.com/ru/post/1683235/


All Articles