· 7 years ago · Apr 24, 2018, 05:00 PM
1@SpringBootApplication
2@RestController
3@EnableOAuth2Client
4public class SocialApplication extends WebSecurityConfigurerAdapter {
5
6 @Autowired
7 OAuth2ClientContext oauth2ClientContext;
8
9 @RequestMapping("/user")
10 public Principal user(Principal principal) {
11 return principal;
12 }
13
14 @Override
15 protected void configure(HttpSecurity http) throws Exception {
16 // @formatter:off
17 http.antMatcher("/**").authorizeRequests().antMatchers("/", "/login**", "/webjars/**").permitAll().anyRequest()
18 .authenticated().and().exceptionHandling()
19 .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/")).and().logout()
20 .logoutSuccessUrl("/").permitAll().and().csrf()
21 .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
22 .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
23 // @formatter:on
24 }
25
26 public static void main(String[] args) {
27 SpringApplication.run(SocialApplication.class, args);
28 }
29
30 @Bean
31 public FilterRegistrationBean<OAuth2ClientContextFilter> oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
32 FilterRegistrationBean<OAuth2ClientContextFilter> registration = new FilterRegistrationBean<OAuth2ClientContextFilter>();
33 registration.setFilter(filter);
34 registration.setOrder(-100);
35 return registration;
36 }
37
38 private Filter ssoFilter() {
39 OAuth2ClientAuthenticationProcessingFilter facebookFilter = new OAuth2ClientAuthenticationProcessingFilter(
40 "/login/facebook");
41 OAuth2RestTemplate facebookTemplate = new OAuth2RestTemplate(facebook(), oauth2ClientContext);
42 facebookFilter.setRestTemplate(facebookTemplate);
43 UserInfoTokenServices tokenServices = new UserInfoTokenServices(facebookResource().getUserInfoUri(),
44 facebook().getClientId());
45 tokenServices.setRestTemplate(facebookTemplate);
46 facebookFilter.setTokenServices(
47 new UserInfoTokenServices(facebookResource().getUserInfoUri(), facebook().getClientId()));
48 return facebookFilter;
49 }
50
51 @Bean
52 @ConfigurationProperties("facebook.client")
53 public AuthorizationCodeResourceDetails facebook() {
54 return new AuthorizationCodeResourceDetails();
55 }
56
57 @Bean
58 @ConfigurationProperties("facebook.resource")
59 public ResourceServerProperties facebookResource() {
60 return new ResourceServerProperties();
61 }
62
63}
64
65<!doctype html>
66<html lang="en">
67<head>
68 <meta charset="utf-8"/>
69 <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
70 <title>Demo</title>
71 <meta name="description" content=""/>
72 <meta name="viewport" content="width=device-width"/>
73 <base href="/"/>
74 <link rel="stylesheet" type="text/css"
75 href="/webjars/bootstrap/css/bootstrap.min.css"/>
76 <script type="text/javascript" src="/webjars/jquery/jquery.min.js"></script>
77 <script type="text/javascript"
78 src="/webjars/bootstrap/js/bootstrap.min.js"></script>
79</head>
80<body>
81<h1>Login</h1>
82<div class="container unauthenticated">
83 With Facebook: <a href="/login/facebook">click here</a>
84</div>
85<div class="container authenticated" style="display: none">
86 Logged in as: <span id="user"></span>
87 <div>
88 <button onClick="logout()" class="btn btn-primary">Logout</button>
89 </div>
90</div>
91<script type="text/javascript"
92 src="/webjars/js-cookie/js.cookie.js"></script>
93<script type="text/javascript">
94 $.ajaxSetup({
95 beforeSend: function (xhr, settings) {
96 if (settings.type == 'POST' || settings.type == 'PUT'
97 || settings.type == 'DELETE') {
98 if (!(/^http:.*/.test(settings.url) || /^https:.*/
99 .test(settings.url))) {
100 // Only send the token to relative URLs i.e. locally.
101 xhr.setRequestHeader("X-XSRF-TOKEN",
102 Cookies.get('XSRF-TOKEN'));
103 }
104 }
105 }
106 });
107 $.get("/user", function (data) {
108 $("#user").html(data.userAuthentication.details.name);
109 $(".unauthenticated").hide();
110 $(".authenticated").show();
111 });
112 var logout = function () {
113 $.post("/logout", function () {
114 $("#user").html('');
115 $(".unauthenticated").show();
116 $(".authenticated").hide();
117 });
118 return true;
119 }
120</script>
121</body>
122</html>
123
124facebook:
125 client:
126 clientId: 233668646673605
127 clientSecret: 33b17e044ee6a4fa383f46ec6e28ea1d
128 accessTokenUri: https://graph.facebook.com/oauth/access_token
129 userAuthorizationUri: https://www.facebook.com/dialog/oauth
130 tokenName: oauth_token
131 authenticationScheme: query
132 clientAuthenticationScheme: form
133 resource:
134 userInfoUri: https://graph.facebook.com/me
135
136logging:
137 level:
138 org.springframework.security: DEBUG
139
140(index):44 Uncaught TypeError: Cannot read property 'details' of undefined
141 at Object.success ((index):44)
142 at j (jquery.js:3073)
143 at Object.fireWith [as resolveWith] (jquery.js:3185)
144 at x (jquery.js:8251)
145 at XMLHttpRequest.<anonymous> (jquery.js:8598)
146
147$.get("/user", function (data) {
148 $("#user").html(data.userAuthentication.details.name);
149 $(".unauthenticated").hide();
150 $(".authenticated").show();
151 });
152
153OAuth2ClientAuthenticationProcessingFilter facebookFilter = new OAuth2ClientAuthenticationProcessingFilter(
154 "/login/facebook");
155OAuth2RestTemplate facebookTemplate = new OAuth2RestTemplate(facebook(), oauth2ClientContext);
156facebookFilter.setRestTemplate(facebookTemplate);
157UserInfoTokenServices tokenServices = new UserInfoTokenServices(facebookResource().getUserInfoUri(),
158 facebook().getClientId());
159tokenServices.setRestTemplate(facebookTemplate);
160facebookFilter.setTokenServices(
161 new UserInfoTokenServices(facebookResource().getUserInfoUri(), facebook().getClientId()));
162return facebookFilter;
163
164private Filter ssoFilter(ClientResources client, String path) {
165 OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(
166 path);
167 OAuth2RestTemplate template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
168 filter.setRestTemplate(template);
169 UserInfoTokenServices tokenServices = new UserInfoTokenServices(
170 client.getResource().getUserInfoUri(), client.getClient().getClientId());
171 tokenServices.setRestTemplate(template);
172 filter.setTokenServices(tokenServices);
173 return filter;
174}