Switched from the manual implemented authentication-layer to Spring Security
[examples/facebook-app] / src / main / java / de / juplo / yourshouter / SpringSecuritySignInAdapter.java
1 package de.juplo.yourshouter;
2
3
4 import org.slf4j.Logger;
5 import org.slf4j.LoggerFactory;
6 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
7 import org.springframework.security.core.context.SecurityContext;
8 import org.springframework.security.core.context.SecurityContextHolder;
9 import org.springframework.social.connect.Connection;
10 import org.springframework.social.connect.web.SignInAdapter;
11 import org.springframework.stereotype.Service;
12 import org.springframework.web.context.request.NativeWebRequest;
13
14
15 /**
16  * Simple implementation of {@link SignInAdapter}.
17  *
18  * This implementation signes in the user by storing him in the
19  * {@link SecurityContext} provided by Spring-Security, using the user-ID as
20  * principal.
21  *
22  * We configured Spring-Social to call this implementation, to sign in the
23  * user, after he was authenticated by Facebook.
24  *
25  * @author Kai Moritz
26  */
27 @Service
28 public class SpringSecuritySignInAdapter implements SignInAdapter
29 {
30   private final static Logger LOG =
31       LoggerFactory.getLogger(SpringSecuritySignInAdapter.class);
32
33   /**
34    * Stores the user in the {@link SecurityContext} provided by Spring Security
35    * to sign him in. Spring Security will automatically persist the
36    * authentication in the user-session for subsequent requests.
37    *
38    * @param user
39    *     The user-ID. We configured Spring-Social to call
40    *     {@link UserCookieSignInAdapter} to extract a user-ID from the
41    *     connection.
42    * @param connection
43    *     The connection. In our case a connection to Facebook.
44    * @param request
45    *     The actual request. We need it, to store the cookie.
46    * @return
47    *     We return <code>null</code>, to indicate, that the user should be
48    *     redirected to the default-post-sign-in-URL (configured in
49    *     {@link ProviderSinInController}) after a successfull authentication.
50    *
51    * @see {@link ProviderSignInController#postSignInUrl}
52    */
53   @Override
54   public String signIn(
55       String user,
56       Connection<?> connection,
57       NativeWebRequest request
58       )
59   {
60     LOG.info(
61         "signing in user {} (connected via {})",
62         user,
63         connection.getKey().getProviderId()
64         );
65
66     SecurityContextHolder.getContext().setAuthentication(
67         new UsernamePasswordAuthenticationToken(user, null, null));
68
69     // We return null to trigger a redirect to "/".
70     return null;
71   }
72 }