Saturday, June 23, 2018

java - handle session expired event in spring based web application




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.



 


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


Answer




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 element:








class="com.example.spring.security.AjaxAwareAuthenticationEntryPoint">



No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...