Spring security handle AJAX XHR request for logout users and response 401 instead of 302

I found this article with filter implementation:

Spring Security part VI : Session Timeout handling for Ajax calls

However in comment someone point that we can simply extend “LoginUrlAuthenticationEntryPoint”.

My solution sets only status 401 and doesn’t write anything to response body:

	static class AjaxAwareLoginUrlAuthenticationEntryPoint
			extends LoginUrlAuthenticationEntryPoint {

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

		public void commence(HttpServletRequest request, HttpServletResponse response,
				AuthenticationException authException) throws IOException, ServletException {

			if (isAjaxRequest(request) && authException != null) {
				response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
				response.flushBuffer();
				return;
			}
			super.commence(request, response, authException);
		}

		private static boolean isAjaxRequest(HttpServletRequest request) {
			return "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"));
		}
	}

Workaround for “X-Forwarded” headers in Spring UriComponentsBuilder

When our application server user proxy, that doesn’t set “X-Forwarded” headers with original request port, then we can use some hack in our application. Just ignore port when it is equal 80 or 443, cause it is default. For example instead of "http://localhost:80/app", we will get "http://localhost/app". And "https://localhost:443/app" will output "https://localhost/app".

UriComponentsBuilder currentUrl = ServletUriComponentsBuilder
					.fromCurrentRequest();
int port = currentUrl.build().getPort();
currentUrl.port(port != 80 && port != 443 ? port : -1);
String currentUrlString = currentUrl.toUriString();

Inspired by Mat Banik strackoverflow answer – http://stackoverflow.com/a/5212336/5770135.