spring-security - 如何在 Spring Security 中设置自定义无效 session 策略

标签 spring-security

我正在开发基于 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);
            }
        });
    }

}

要求是在 session 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;
    }
}

关于spring-security - 如何在 Spring Security 中设置自定义无效 session 策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25809367/

相关文章:

Spring 安全: Controller method access to certain roles

java - 嵌入式 Jetty 环境中的 Spring Boot 和 Spring Security 集成

java - Spring Boot 安全登录 (v4)

java - 成功登录时发送自定义对象作为响应以及状态代码 200,无需内部重定向

java - 如何从基于 Spring security 的应用程序创建访问表?

java - 如何在 Spring Security OAuth2 中生成没有 client_secret 的 token

java - 如何在 Spring Security 中替换 UsernamePasswordAuthenticationFilter

java - Spring Security 的 Thymeleaf 授权不起作用

grails - 使用Spring Security Core 3.0.0M1创建登录名

java - 在 Spring 安全性中保护具有相同角色的用户之间的 Controller