Redirect handling PrimeFaces Ajax requests on session timeout in Spring Security

亡梦爱人 提交于 2019-12-02 18:39:35
rachekalmir

This is a problem with the default way that Spring Security sends redirects back to the client. The default method of sending a redirect to the client is the HTML approach of sending a 302 Temporarily Moved response, however this does not work for AJAX clients. The AJAX client will interpret this as a redirect to a new location to post/get its data and not as a page redirect. The correct way to get the AJAX client to redirect the browser to a new page in the same way as a normal HTML request is:

<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<partial-response>
  <redirect url="http://your.url.here/"></redirect>
</partial-response>

To override the default invalid session strategy used by Spring Security, you need to create a SessionManagementFilter bean in your Spring config, and pass it a class that implements InvalidSessionStrategy and sends the correct redirect response when a request is received either via HTML or AJAX:

<bean id="sessionManagementFilter" class="org.springframework.security.web.session.SessionManagementFilter">
  <constructor-arg name="securityContextRepository" ref="httpSessionSecurityContextRepository" />
  <property name="invalidSessionStrategy">
    <bean class="yourpackage.JsfRedirectStrategy">
       <constructor-arg name="invalidSessionUrl" value="/your_session_expired_page.xhtml" />
    </bean>
  </property>
</bean>
<bean id="httpSessionSecurityContextRepository" class="org.springframework.security.web.context.HttpSessionSecurityContextRepository"/>

You then need to add this filter to your Spring Security HTTP block:

<security:http use-expressions="true">
    <security:custom-filter ref="sessionManagementFilter" before="SESSION_MANAGEMENT_FILTER" />
    ...
</security:http>

The custom session management filter will now be created when your application starts, and the invalid session strategy class provided will execute whenever an expired session is found.

A good example of how to implement the invalid session strategy can be found here: https://gist.github.com/banterCZ/5160269

A similar question using IceFaces is available here: JSF 2, Spring Security 3.x and Richfaces 4 redirect to login page on session time out for ajax requests

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