Spring安全无效会话重定向



我在spring boot 1.2.3 web应用程序中使用spring security 4.0.1(也使用spring-session 1.0.1,但这与案例无关)。

我确实有一个私人区域,和一个所有访问区域("/about","/","/contact",…超过20页),每个用户都可以访问。(它就像一个网上商店)

每当登录的用户会话过期时,Spring检测到无效会话并将用户重定向到'.invalidSessionUrl("/session/error/invalid")'

但是,如果目标链接在私有区域内,而不是公共区域内,我只想被重定向。

我怎样才能避免呢?

谢谢。

这是我的(java)配置:(更新后看到的帖子)

 http
            .authorizeRequests()
            .anyRequest()
                .permitAll()
            .antMatchers("/privado/**")
                .authenticated()
            .and()
                .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error")
                .defaultSuccessUrl("/")
                .successHandler(new SessionSuccessHandler())
            .and()
                .logout()
                .logoutSuccessUrl("/")
                .deleteCookies("JSESSIONID", "SESSION")
            .and()
                .sessionManagement()
                .invalidSessionUrl("/session/error/invalid")
            .sessionFixation()
            .changeSessionId()
            .maximumSessions(1)
            .expiredUrl("/session/error/expired")
            .and()
            .and()
                .csrf()
                .ignoringAntMatchers("/jolokia/**", "/v1.0/**");

我该怎么做呢?

另一个解决方法是在与您类似的情况下处理此问题,将过期/无效会话策略添加到您的配置中,如下所示:

http
    .expiredSessionStrategy(e -> {
        handleExpiredInvalidSessions(e.getRequest(), e.getResponse());
    })
    .sessionRegistry(sessionRegistry())
    .and()
    .invalidSessionStrategy((request, response) -> {
        handleExpiredInvalidSessions(request, response);
    })
然后您将实现它以匹配公共uri并简单地转发请求
private void handleExpiredInvalidSessions(HttpServletRequest request, HttpServletResponse response) {
    String requestUri = request.getRequestURI();
    if (isPublicURI(requestUri)) {
        // This will remove the invalid/expired session from the request
        // and prevent the request from failing again
        request.getSession(true).invalidate();
        RequestDispatcher dispatcher = request.getRequestDispatcher(requestUri);
        // Retry the request
        dispatcher.forward(request, response);
    } else {
        // might redirect if you wish
        response.setStatus(440);
    }
}

你仍然需要实现isPublicURI()取决于你想要的公共路径,在我的情况下,它只有一个路径,所以它很容易。

@RobWinch -这似乎是一个非常常见的用例,您提出的解决方案似乎无法从我运行的测试和评论中工作。类似的问题在http://forum.spring.io/forum/spring-projects/security/94772-redirect-to-invalid-session-url-only-when-user-accesses-secured-resource上也出现过,但似乎从未得到解决。我的想法是有多个http设置(使用xml配置)

<http pattern="/aboutUs**" security="none" />
<http pattern="/contact**" security="none" />
etc

当有相当多的不安全页面并且添加新的不安全页面需要更新配置时,这似乎不理想。如果我们能为这个用例提供一个"理想"的解决方案,那就太好了。在Spring security 4.1版本中,似乎仍然没有明确的方法来做到这一点。

您可以提供自定义SessionAuthenticationStrategy来完成此操作。例如:

public class MatcherSessionAuthenticationStrategy implements SessionAuthenticationStrategy {
    private final SessionAuthenticationStrategy delegate;
    private final RequestMatcher matcher;
    public MatcherSessionAuthenticationStrategy(
            SessionAuthenticationStrategy delegate, RequestMatcher matcher) {
        super();
        this.delegate = delegate;
        this.matcher = matcher;
    }
    public void onAuthentication(Authentication authentication,
            HttpServletRequest request, HttpServletResponse response)
            throws SessionAuthenticationException {
        if(matcher.matches(request)) {
            delegate.onAuthentication(authentication, request, response);
        }
    }
}

然后你可以注入RequestMatcher和ConcurrentSessionControlAuthenticationStrategy到类中。最简单的配置方法是创建一个BeanPostProcessor:

public class ConcurrentSessionControlAuthenticationStrategyBeanPostProcessor
        implements BeanPostProcessor {
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        return bean;
    }
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        if(!(bean instanceof CompositeSessionAuthenticationStrategy)) {
            return bean;
        }
        RequestMatcher matcher = antMatchers("/about", "/","/contact");
        SessionAuthenticationStrategy original = (SessionAuthenticationStrategy) bean;
        return new MatcherSessionAuthenticationStrategy(original, matcher);
    }
    /**
     * Create a {@link List} of {@link AntPathRequestMatcher} instances.
     *
     * @param httpMethod the {@link HttpMethod} to use or {@code null} for any
     * {@link HttpMethod}.
     * @param antPatterns the ant patterns to create {@link AntPathRequestMatcher}
     * from
     *
     * @return an OrRequestMatcher with a {@link List} of {@link AntPathRequestMatcher} instances
     */
    public static RequestMatcher antMatchers(
            String... antPatterns) {
        List<RequestMatcher> matchers = new ArrayList<RequestMatcher>();
        for (String pattern : antPatterns) {
            matchers.add(new AntPathRequestMatcher(pattern));
        }
        return new OrRequestMatcher(matchers);
    }
}

然后你可以在你的配置中添加以下内容:

@Bean
public static BeanPostProcessor sessionBeanPostProcessor() {
    return new ConcurrentSessionControlAuthenticationStrategyBeanPostProcessor();
}

使用静态方法是很重要的,因为这是一个BeanPostProcessor,需要在早期初始化。

附言:我会考虑按照这篇博客

的概述来格式化你的配置。

相关内容

  • 没有找到相关文章

最新更新