Redirect to originally requested page after sign-in
[examples/facebook-app] / src / main / java / de / juplo / yourshouter / SocialAuthenticationEntryPoint.java
index 4c3671c..f119314 100644 (file)
@@ -4,6 +4,7 @@ import java.io.IOException;
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.security.core.AuthenticationException;
@@ -24,12 +25,24 @@ public class SocialAuthenticationEntryPoint implements AuthenticationEntryPoint
   private static final Logger LOG =
       LoggerFactory.getLogger(SocialAuthenticationEntryPoint.class);
 
+  public final static String REDIRECT_ATTRIBUTE =
+      SocialAuthenticationEntryPoint.class.getCanonicalName() + ".REDIRECT";
+
 
   /**
    * {@inheritDoc}
    *
-   * To commence the sign-in through the Graph-API, we only have to redirect
+   * To commence the sign-in through the Graph-API, we have to redirect
    * to our already implemented sign-in-page.
+   * <p>
+   * We store the originally requested page in the {@link HttpSession}, to be
+   * redirect back to that page after a successful authentication in
+   * {@link SpringSecuritySignInAdapter}.
+   * <p>
+   * Only the first request of a ressource, that requires authentication, will
+   * trigger the redirect to the sing-in-page.
+   *
+   * @see SpringSecuritySignInAdapter
    */
   @Override
   public void commence(
@@ -41,10 +54,29 @@ public class SocialAuthenticationEntryPoint implements AuthenticationEntryPoint
         IOException,
         ServletException
   {
-    LOG.info(
-        "redirecting unauthenticated request {} to /signin.html",
-        request.getRequestURI()
-        );
-    response.sendRedirect("/signin.html");
+    HttpSession session = request.getSession();
+    if (session.getAttribute(REDIRECT_ATTRIBUTE) == null)
+    {
+      LOG.info(
+          "redirecting unauthenticated request to {}",
+          request.getRequestURI()
+          );
+      StringBuffer url = request.getRequestURL();
+      if (request.getQueryString() != null)
+      {
+        url.append('?');
+        url.append(request.getQueryString());
+      }
+      session.setAttribute(REDIRECT_ATTRIBUTE, url.toString());
+      response.sendRedirect("/signin.html");
+    }
+    else
+    {
+      LOG.info(
+          "redirect to sign-in already in progress, forbidding access to {}",
+          request.getRequestURI()
+          );
+      response.sendError(HttpServletResponse.SC_FORBIDDEN);
+    }
   }
 }