Spring

From Jujunie Wiki
Jump to: navigation, search

AngularJS and Spring security: Session timeout on Ajax request

Step 1: Customise default HTTP headers in Angular, and implement a response interceptor

var ang = angular.module("exampleApp", [], function($provide, $httpProvider) { // Response interceptor $provide.factory("myHttpInterceptor",function($q, $window) { return function(promise) { return promise.then( function(response) { return response; }, function(response) { $window.location.reload(); } ); } }); $httpProvider.responseInterceptors.push("myHttpInterceptor"); // Adding header to identify AJAX request $httpProvider.defaults.headers.common["X-ats-type"] = "ajax"; });

Step 2: Create a [AuthenticationEntryPoint http://static.springsource.org/spring-security/site/docs/3.1.x/apidocs/org/springframework/security/web/AuthenticationEntryPoint.html] implementation (here extends [LoginUrlAuthenticationEntryPoint http://static.springsource.org/spring-security/site/docs/3.1.x/apidocs/org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPoint.html])

/**

* Custom AuthenticationEntryPoint which detects an Ajax request to send an error code rather than redirecting
* to the login page
*/

public class AjaxAwareAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {

private static final Logger LOG = LoggerFactory.getLogger(AjaxAwareAuthenticationEntryPoint.class);

public AjaxAwareAuthenticationEntryPoint(String loginFormUrl) { super(loginFormUrl); }

@Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { LOG.debug("commence"); if ("ajax".equals(request.getHeader("X-ats-type"))) { LOG.debug("AJAX request detected - sending error code."); response.sendError(601, "Session Timeout"); } else { LOG.debug("Delegating processing to parent class"); super.commence(request, response, authException); } }

}

Step 3: Registering in Spring configuration

 <bean id="ajaxAwareAuthenticationEntryPoint" class="com.example.AjaxAwareAuthenticationEntryPoint">
   <constructor-arg value="/login.jsp"/>
 </bean>
 ...
 <http auto-config="true" entry-point-ref="ajaxAwareAuthenticationEntryPoint">
   <intercept-url pattern="/**" access="${role.access}" />
   <form-login default-target-url="/#"
               always-use-default-target="false"
               password-parameter="pwd"
               username-parameter="login"/>
   <logout logout-url="/logout" logout-success-url="/#"/>
 </http>

Sources: