【问题标题】:handle session expired event in spring based web application在基于 Spring 的 Web 应用程序中处理会话过期事件
【发布时间】:2012-06-29 19:51:35
【问题描述】:
我在我的应用程序中使用 Spring 安全功能,但我发现当会话过期时,所有请求 ajax 都返回页面 login.jsp(不是重定向,在 http 响应中,它放置所有 html 内容)这是我的 webapp 的登录页面。
我在我的应用程序中使用了很多 ajax 请求,目标是返回某些错误代码,例如 510,而不是登录页面。
<session-management session-authentication-strategy-ref="example" />
没有无效会话 url
我试图使 invalid-session-url = "",不起作用。
非常感谢
【问题讨论】:
标签:
java
spring
spring-security
session-timeout
【解决方案1】:
使用自定义AuthenticationEntryPoint:
package com.example.spring.security
// imports here
public class AjaxAwareAuthenticationEntryPoint
extends LoginUrlAuthenticationEntryPoint {
public AjaxAwareAuthenticationEntryPoint(final String loginFormUrl) {
super(loginFormUrl);
}
@Override
public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException)
throws IOException, ServletException {
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
response.sendError(403, "Forbidden");
} else {
super.commence(request, response, authException);
}
}
}
定义一个bean并将其用作entry-point-ref in <http> element:
<http entry-point-ref="authenticationEntryPoint">
<!-- more configuration here -->
</http>
<bean id="authenticationEntryPoint"
class="com.example.spring.security.AjaxAwareAuthenticationEntryPoint">
<constructor-arg value="/login.jsp"/>
</bean>