Redirect to originally requested page after sign-in
[examples/facebook-app] / src / main / java / de / juplo / yourshouter / SpringSecuritySignInAdapter.java
index 05c978b..24cf904 100644 (file)
@@ -1,6 +1,8 @@
 package de.juplo.yourshouter;
 
 
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@@ -31,23 +33,20 @@ public class SpringSecuritySignInAdapter implements SignInAdapter
       LoggerFactory.getLogger(SpringSecuritySignInAdapter.class);
 
   /**
+   * {@inheritDoc}
+   *
    * Stores the user in the {@link SecurityContext} provided by Spring Security
    * to sign him in. Spring Security will automatically persist the
    * authentication in the user-session for subsequent requests.
+   * <p>
+   * If an originally requested ressource was stored in the {@link HttpSession}
+   * by the {@link SocialAuthenticationEntryPoint}, that URL will be returned,
+   * so that the {@link RequestCache} can restore the request.
+   * Otherwise, <code>null</code> will be returned, to indicate, that the user
+   * should be redirected to the default-post-sign-in-URL (configured in
+   * {@link ProviderSinInController}) after a successfull authentication.
    *
-   * @param user
-   *     The user-ID. We configured Spring-Social to call
-   *     {@link UserCookieSignInAdapter} to extract a user-ID from the
-   *     connection.
-   * @param connection
-   *     The connection. In our case a connection to Facebook.
-   * @param request
-   *     The actual request. We need it, to store the cookie.
-   * @return
-   *     We return <code>null</code>, to indicate, that the user should be
-   *     redirected to the default-post-sign-in-URL (configured in
-   *     {@link ProviderSinInController}) after a successfull authentication.
-   *
+   * @see {@link SocialAuthenticationEntryPoint}
    * @see {@link ProviderSignInController#postSignInUrl}
    */
   @Override
@@ -66,7 +65,20 @@ public class SpringSecuritySignInAdapter implements SignInAdapter
     SecurityContextHolder.getContext().setAuthentication(
         new UsernamePasswordAuthenticationToken(user, null, null));
 
-    // We return null to trigger a redirect to "/".
-    return null;
+    HttpSession session =
+        request.getNativeRequest(HttpServletRequest.class).getSession();
+    String redirect =
+        (String)session
+            .getAttribute(SocialAuthenticationEntryPoint.REDIRECT_ATTRIBUTE);
+    if (redirect != null)
+    {
+      LOG.info("redirecting to originally requested resource {}", redirect);
+      session.removeAttribute(SocialAuthenticationEntryPoint.REDIRECT_ATTRIBUTE);
+    }
+    else
+    {
+      LOG.info("found no original request in session, redirecting to default");
+    }
+    return redirect;
   }
 }