Redirect to originally requested page after sign-in
[examples/facebook-app] / src / main / java / de / juplo / yourshouter / SocialAuthenticationEntryPoint.java
1 package de.juplo.yourshouter;
2
3 import java.io.IOException;
4 import javax.servlet.ServletException;
5 import javax.servlet.http.HttpServletRequest;
6 import javax.servlet.http.HttpServletResponse;
7 import javax.servlet.http.HttpSession;
8 import org.slf4j.Logger;
9 import org.slf4j.LoggerFactory;
10 import org.springframework.security.core.AuthenticationException;
11 import org.springframework.security.web.AuthenticationEntryPoint;
12 import org.springframework.stereotype.Service;
13
14
15 /**
16  * Specialized implementation of {@link AuthenticationEntryPoint}, that
17  * redirects to the social sign-in-page, to let the user decide to sign in or
18  * not.
19  *
20  * @author Kai Moritz
21  */
22 @Service
23 public class SocialAuthenticationEntryPoint implements AuthenticationEntryPoint
24 {
25   private static final Logger LOG =
26       LoggerFactory.getLogger(SocialAuthenticationEntryPoint.class);
27
28   public final static String REDIRECT_ATTRIBUTE =
29       SocialAuthenticationEntryPoint.class.getCanonicalName() + ".REDIRECT";
30
31
32   /**
33    * {@inheritDoc}
34    *
35    * To commence the sign-in through the Graph-API, we have to redirect
36    * to our already implemented sign-in-page.
37    * <p>
38    * We store the originally requested page in the {@link HttpSession}, to be
39    * redirect back to that page after a successful authentication in
40    * {@link SpringSecuritySignInAdapter}.
41    * <p>
42    * Only the first request of a ressource, that requires authentication, will
43    * trigger the redirect to the sing-in-page.
44    *
45    * @see SpringSecuritySignInAdapter
46    */
47   @Override
48   public void commence(
49       HttpServletRequest request,
50       HttpServletResponse response,
51       AuthenticationException exception
52       )
53       throws
54         IOException,
55         ServletException
56   {
57     HttpSession session = request.getSession();
58     if (session.getAttribute(REDIRECT_ATTRIBUTE) == null)
59     {
60       LOG.info(
61           "redirecting unauthenticated request to {}",
62           request.getRequestURI()
63           );
64       StringBuffer url = request.getRequestURL();
65       if (request.getQueryString() != null)
66       {
67         url.append('?');
68         url.append(request.getQueryString());
69       }
70       session.setAttribute(REDIRECT_ATTRIBUTE, url.toString());
71       response.sendRedirect("/signin.html");
72     }
73     else
74     {
75       LOG.info(
76           "redirect to sign-in already in progress, forbidding access to {}",
77           request.getRequestURI()
78           );
79       response.sendError(HttpServletResponse.SC_FORBIDDEN);
80     }
81   }
82 }