handle session expired event in spring based web application

你说的曾经没有我的故事 提交于 2019-12-29 06:36:45

问题


I am using Spring security feature in my application, but I found out that when the session expired, all the request ajax return the page login.jsp(not redirect, in http response, it puts all the html content) which is the login page of my webapp. I used a lot of ajax request in my app and the goal is return certain error code like 510 instead of the login page.

<session-management session-authentication-strategy-ref="example" /> 

without invalid-session-url I tried to make invalid-session-url = "", doesn't work. Many thanks


回答1:


Use custom 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);
    }
  }
}

Define a bean and use it as 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>


来源:https://stackoverflow.com/questions/11242174/handle-session-expired-event-in-spring-based-web-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!