How to use the request Referer as the targetUrl when using Acegi Security for Spring

2 min read >

How to use the request Referer as the targetUrl when using Acegi Security for Spring

Engineering Insights & Enterprise solutions

Suppose that my login form is integrated into another page and I want to return to that page that integrated my login page (so the original page).
How do you do that in ACEGI?

My solution was to extend the AuthenticationProcessingFilter and add a property named useRefererAsTargetUrl.
If this property is set to true, then the AuthenticationProcessingFilter will redirect to the value of the request Referer header upon successful authentication, unless the targetUrl can be taken from a SavedRequest, (which usually means that the authentication request was caused by an AccessDeniedException or AuthenticationException thrown within the filter chain). If alwaysUseDefaultTargetUrl is also set to true, then the defaultTargetUrl will be used, and this flag will be ignored.
This flag defaults to false, which is the default behavior of AuthenticationProcessingFilter.

The source code for the class is as follows:

public class ExtendedAuthenticationProcessingFilter extends AuthenticationProcessingFilter {
 
    /**
     * If <code>true</code>, will redirect to the value of the request Referer header upon successful authentication, * unless the targetUrl can be taken from a {@link org.acegisecurity.ui.savedrequest.SavedRequest} * (which usually means that the authentication request was caused by an * <code>AccessDeniedException</code> or <code>AuthenticationException</code> thrown within the filter chain). * If alwaysUseDefaultTargetUrl is also set to true, then the defaultTargetUrl will be used, * and this flag will be ignored. * This flag defaults to <code>false</code>, which is the default behaviour of AuthenticationProcessingFilter. */ private boolean useRefererAsTargetUrl = false; protected String determineTargetUrl(HttpServletRequest request) { // Don't attempt to obtain the url from the saved request if // alwaysUsedefaultTargetUrl is set if (isAlwaysUseDefaultTargetUrl()) { return getDefaultTargetUrl(); } String targetUrl = obtainFullRequestUrl(request); if (targetUrl == null &amp;&amp; useRefererAsTargetUrl) { targetUrl = obtainRequestRefererUrl(request); } if (targetUrl == null) { targetUrl = getDefaultTargetUrl(); } return targetUrl; } public static String obtainRequestRefererUrl(HttpServletRequest request) { return request.getHeader(HttpUtils.HTTP_HEADER_REFERER); } public boolean isUseRefererAsTargetUrl() { return useRefererAsTargetUrl; } public void setUseRefererAsTargetUrl(boolean useRefererAsTargetUrl) { this.useRefererAsTargetUrl = useRefererAsTargetUrl; } }

Maybe (in a future release of Acegi Security) this feature will simply be integrated into AbstractProcessingFilter, where it belongs…