]> juplo.de Git - website/blob
2f571ba57bf21fe42375c95a5c0ae917b9e28b10
[website] /
1 ---
2 _edit_last: "2"
3 author: kai
4 categories:
5   - howto
6 date: "2016-01-26T14:34:23+00:00"
7 guid: http://juplo.de/?p=644
8 parent_post_id: null
9 post_id: "644"
10 tags:
11   - createmedia.nrw
12   - facebook
13   - graph-api
14   - java
15   - oauth2
16   - spring
17   - spring-boot
18   - spring-social
19 title: 'Develop a Facebook-App with Spring-Social – Part V: Refactor The Redirect-Logic'
20 url: /develop-a-facebook-app-with-spring-social-part-05-refactor-the-redirect-logic/
21
22 ---
23 In this series of Mini-How-Tow's I will describe how to develop a facebook app with the help of [Spring-Social](http://projects.spring.io/spring-social/ "Learn more about Spring-Social")
24
25 In [the last part of this series](/develop-a-facebook-app-with-spring-social-part-04-signing-in-users "Go back to part 4 of this series, to learn how to sign in users"), we reconfigured our app, so that users are signed in after an authentication against Facebook and new users are signed up automatically on the first visit.
26
27 In this part, we will refactor our redirect-logic for unauthenticated users, so that it more closely resembles the behavior of Spring Social, hence, easing the planed switch to that technology in a feature step.
28
29 ## The Source is With You
30
31 You can find the source-code on [/git/examples/facebook-app/](/git/examples/facebook-app/ "Link for cloning")
32 and [browse it via gitweb](/gitweb/?p=examples/facebook-app;a=summary "Browse the source-code now").
33 Check out `part-05` to get the source for this part of the series.
34
35 ## Mimic Spring Security
36
37 **To stress that again: our simple authentication-concept is only meant for educational purposes. [It is inherently insecure!](/develop-a-facebook-app-with-spring-social-part-03-implementing-a-user-id-source#remember "Jump back to part 3 to learn, why our authentication-concept is insecure")**
38 We are not refining it here, to make it better or more secure.
39 We are refining it, so that it can be replaced with Spring Security later on, without a hassle!
40
41 In our current implementation, a user, who is not yet authenticated, would be redirected to our sign-in-page only, if he visits the root of our webapp ( `/`).
42 To move all redirect-logic out of `HomeController` and redirect unauthenicated users from all pages to our sign-in-page, we can simply modify our interceptor `UserCookieInterceptor`, which already intercepts each and every request.
43
44 We refine the method `preHandle`, so that it redirects every request to our sign-in-page, that is not authenticated:
45
46 ```Java
47 @Override
48 public boolean preHandle(
49     HttpServletRequest request,
50     HttpServletResponse response,
51     Object handler
52     )
53     throws
54       Exception
55 {
56   if (request.getServletPath().startsWith("/signin"))
57     return true;
58
59   String user = UserCookieGenerator.INSTANCE.readCookieValue(request);
60   if (user != null)
61   {
62     if (!repository
63         .findUserIdsConnectedTo("facebook", Collections.singleton(user))
64         .isEmpty()
65         )
66     {
67       LOG.info("loading user {} from cookie", user);
68       SecurityContext.setCurrentUser(user);
69       return true;
70     }
71     else
72     {
73       LOG.warn("user {} is not known!", user);
74       UserCookieGenerator.INSTANCE.removeCookie(response);
75     }
76   }
77
78   response.sendRedirect("/signin.html");
79   return false;
80 }
81
82 ```
83
84 If the user, that is identified by the cookie, is not known to Spring Security, we send a redirect to our sign-in-page and flag the request as already handled, by returning `false`.
85 To prevent an endless loop of redirections, we must not redirect request, that were already redirected to our sign-in-page.
86 Since these requests hit our webapp as a new request for the different location, we can filter out and wave through at the beginning of this method.
87
88 ## Run It!
89
90 That is all there is to do.
91 Run the app and call the page `http://localhost:8080/profile.html` as first request.
92 You will see, that you will be redirected to our sigin-in-page.
93
94 ## Cleaning Up Behind Us...
95
96 As it is now not possible, to call any page except the sigin-up-page, without beeing redirected to our sign-in-page, if you are not authenticated, it is impossible to call any page without being authenticated.
97 Hence, we can (and should!) refine our `UserIdSource`, to throw an exception, if that happens anyway, because it has to be a sign for a bug:
98
99 ```Java
100 public class SecurityContextUserIdSource implements UserIdSource
101 {
102
103   @Override
104   public String getUserId()
105   {
106     Assert.state(SecurityContext.userSignedIn(), "No user signed in!");
107     return SecurityContext.getCurrentUser();
108   }
109 }
110
111 ```
112
113 ## Coming Next...
114
115 In the next part of this series, we will enable users to sign in through the canvas-page of our app.
116 The canvas-page is the page that Facebook embeds into its webpage, if we render our app inside of Facebook.
117
118 ## Funded by the Europian Union
119
120 This article was published in the course of a
121 [resarch-project](http://yourshouter.com/projekte/crowdgest%C3%BCtzte-veranstaltungs-suchmaschine.html "Show details about the funded resarch-project"),
122 that is funded by the European Union and the federal state Northrhine-Wetphalia.
123
124 [![Europäische Union: Investitionen in unsere Zukunft - Europäischer Fonds für regionale Entwicklung](/img/EFRE_Foerderhinweis_deutsch_farbig.svg)![EFRE.NRW 2014-2020: Invesitionen in Wachstum und Beschäftigung](/img/Ziel2NRW_4c_1809_eps.svg)](http://yourshouter.com/projekte/crowdgest%C3%BCtzte-veranstaltungs-suchmaschine.html "Show details about the funded resarch-project")