如何在 Spring Security 中设置自定义无效会话策略

2023-11-24

我正在开发一个基于 Spring-Boot - 1.1.6、Spring -Security -3.2.5 等的 Web 应用程序。

我正在使用基于 Java 的配置:

@Configuration
@EnableWebMvcSecurity
public class SecurityCtxConfig extends WebSecurityConfigurerAdapter {


    @Bean
    DelegatingAuthenticationEntryPoint delegatingAuthenticationEntryPoint() {
        LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> map = new LinkedHashMap<RequestMatcher, AuthenticationEntryPoint>();
        Http403ForbiddenEntryPoint defaultEntryPoint = new Http403ForbiddenEntryPoint();
        map.put(AnyRequestMatcher.INSTANCE, defaultEntryPoint);
        DelegatingAuthenticationEntryPoint retVal = new DelegatingAuthenticationEntryPoint(map);
        retVal.setDefaultEntryPoint(defaultEntryPoint);
        return retVal;
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ExceptionHandlingConfigurer<HttpSecurity> exceptionHandling = http.exceptionHandling();
        exceptionHandling.authenticationEntryPoint(delegatingAuthenticationEntryPoint());
        http.logout().logoutSuccessHandler(new LogoutSuccessHandler() {

            @Override
            public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication arg2)
                    throws IOException, ServletException {
                response.setStatus(HttpServletResponse.SC_OK);
            }
        });
    }

}

要求是在会话 cookie 无效或丢失(无论原因为何)的情况下返回 Http 状态 401 我看到InvalidSessionStrategy但我没有找到一种方法来设置它SessionManagementFilter。 有人可以指导我如何实施我的计划或另一个能够满足要求的计划吗


使用 SpringBoot 这对我有用:

@Configuration
@EnableWebSecurity
public class UISecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ...
        http.addFilterAfter(expiredSessionFilter(), SessionManagementFilter.class);
        ...
    }

    private Filter expiredSessionFilter() {
        SessionManagementFilter smf = new SessionManagementFilter(new HttpSessionSecurityContextRepository());
        smf.setInvalidSessionStrategy((request, response) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Session go BOOM!"));               
        return smf;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Spring Security 中设置自定义无效会话策略 的相关文章

随机推荐