How to set a custom invalid session strategy in Spring Security

前端 未结 3 676
心在旅途
心在旅途 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:58

    We had the exact same problem and I did this hack to solve it (yes I know, this is a hack, therefore the name...). I create a BeanPostProcessor and search for the SessionManagementFilter to reconfigure it...

    @Bean
    public HackyBeanPostProcessor myBeanPostProcessor() {
        return new HackyBeanPostProcessor();
    }
    
    protected static class HackyBeanPostProcessor implements BeanPostProcessor {
    
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) {
            // FIXME check if a new spring-security version allows this in an
            // other way (current: 3.2.5.RELEASE)
            if (bean instanceof SessionManagementFilter) {
                SessionManagementFilter filter = (SessionManagementFilter) bean;
                filter.setInvalidSessionStrategy(new InvalidSessionStrategy() {
    
                    @Override
                    public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
                        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                    }
                });
            }
            return bean;
        }
    
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) {
            return bean;
        }
    }
    

提交回复
热议问题