How to set a custom invalid session strategy in Spring Security

前端 未结 3 691
心在旅途
心在旅途 2021-01-05 09:06

I\'m developing a web application, based on Spring-Boot - 1.1.6, Spring -Security -3.2.5 and more.

I\'m using Java based configuration:

@Configuratio         


        
3条回答
  •  难免孤独
    2021-01-05 09:51

    Since I'm using AspectJ (I mean, compile time weaving and not Spring AOP), it was quite easy to hack the SessionManagementFilter creation by setting my custom InvalidSessionStrategy after the SessionManagementFilter is constructed:

    @Aspect
    public class SessionManagementAspect {
        private static final Log logger = LogFactory.getLog();
    
        @AfterReturning("execution( org.springframework.security.web.session.SessionManagementFilter.new(..))&&this(smf)")
        public void creation(JoinPoint pjp, SessionManagementFilter smf) throws Throwable {
            logger.debug("Adding/Replacing the invalid session detection policy to return 401 in case of an invalid session");
            smf.setInvalidSessionStrategy(new InvalidSessionStrategy() {
    
                @Override
                public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
                    logInvalidSession(request, "invalid cookie");
                    if (!response.isCommitted())
                        response.sendError(HttpStatus.UNAUTHORIZED.value());
                }
            });
        }
    }
    

    If you are not using AspectJ, try adding @Component and add this Aspect to your context, it might work if the SessionManagementFilter is a bean (Since Spring-AOP applias only on spring beans)

提交回复
热议问题