我在 spring boot 1.2.3 Web 应用程序中使用 spring security 4.0.1(也使用 spring-session 1.0.1,但这与本例无关)。
我确实有一个私有(private)区域和一个所有用户都可以访问的所有访问区域(“/about”、“/”、“/contact”...超过 20 页)。 (它就像一个网上商店)
每当登录用户 session 过期时,Spring 会检测到无效 session 并将用户重定向到'.invalidSessionUrl("/session/error/invalid")'
但是,我只想在目标链接位于私有(private)区域内而不是公共(public)区域内时被重定向。
我怎样才能避免这种情况?
谢谢。
这是我的(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/**");
我怎样才能做到这一点?
非常感谢。
最佳答案
帮助我在与您类似的情况下处理此问题的另一个解决方法是将过期/无效 session 策略添加到您的配置中,如下所示:
http
.expiredSessionStrategy(e -> {
handleExpiredInvalidSessions(e.getRequest(), e.getResponse());
})
.sessionRegistry(sessionRegistry())
.and()
.invalidSessionStrategy((request, response) -> {
handleExpiredInvalidSessions(request, response);
})
然后您将实现它来匹配公共(public) 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()
根据您想要的公共(public)路径,在我的例子中,它只有一条路径,所以非常简单。
关于spring-mvc - Spring Security 无效 session 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30465618/