· 6 years ago · Dec 10, 2018, 12:12 PM
1@SpringBootApplication
2@RestController
3@EnableOAuth2Client
4@EnableAuthorizationServer
5@Order(200)
6public class SocialApplication extends WebSecurityConfigurerAdapter {
7
8 @Autowired
9 OAuth2ClientContext oauth2ClientContext;
10
11 @RequestMapping({ "/user", "/me" })
12 public Map<String, String> user(Principal principal) {
13 Map<String, String> map = new LinkedHashMap<>();
14 map.put("name", principal.getName());
15 return map;
16 }
17
18 @Override
19 protected void configure(HttpSecurity http) throws Exception {
20 // @formatter:off
21 http.antMatcher("/**").authorizeRequests().antMatchers("/", "/login**", "/webjars/**").permitAll().anyRequest()
22 .authenticated().and().exceptionHandling()
23 .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/")).and().logout()
24 .logoutSuccessUrl("/").permitAll().and().csrf()
25 .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
26 .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
27 // @formatter:on
28 }
29
30 @Configuration
31 @EnableResourceServer
32 protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
33 @Override
34 public void configure(HttpSecurity http) throws Exception {
35 // @formatter:off
36 http.antMatcher("/me").authorizeRequests().anyRequest().authenticated();
37 // @formatter:on
38 }
39 }
40
41 public static void main(String[] args) {
42 SpringApplication.run(SocialApplication.class, args);
43 }
44
45 @Bean
46 public FilterRegistrationBean<OAuth2ClientContextFilter> oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
47 FilterRegistrationBean<OAuth2ClientContextFilter> registration = new FilterRegistrationBean<OAuth2ClientContextFilter>();
48 registration.setFilter(filter);
49 registration.setOrder(-100);
50 return registration;
51 }
52
53 @Bean
54 @ConfigurationProperties("github")
55 public ClientResources github() {
56 return new ClientResources();
57 }
58
59 @Bean
60 @ConfigurationProperties("facebook")
61 public ClientResources facebook() {
62 return new ClientResources();
63 }
64
65 private Filter ssoFilter() {
66 CompositeFilter filter = new CompositeFilter();
67 List<Filter> filters = new ArrayList<>();
68 filters.add(ssoFilter(facebook(), "/login/facebook"));
69 filters.add(ssoFilter(github(), "/login/github"));
70 filter.setFilters(filters);
71 return filter;
72 }
73
74 private Filter ssoFilter(ClientResources client, String path) {
75 OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(
76 path);
77 OAuth2RestTemplate template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
78 filter.setRestTemplate(template);
79 UserInfoTokenServices tokenServices = new UserInfoTokenServices(
80 client.getResource().getUserInfoUri(),
81 client.getClient().getClientId());
82 tokenServices.setRestTemplate(template);
83 filter.setTokenServices(new UserInfoTokenServices(
84 client.getResource().getUserInfoUri(),
85 client.getClient().getClientId()));
86 return filter;
87 }
88
89}
90
91class ClientResources {
92
93 @NestedConfigurationProperty
94 private AuthorizationCodeResourceDetails client = new AuthorizationCodeResourceDetails();
95
96 @NestedConfigurationProperty
97 private ResourceServerProperties resource = new ResourceServerProperties();
98
99 public AuthorizationCodeResourceDetails getClient() {
100 return client;
101 }
102
103 public ResourceServerProperties getResource() {
104 return resource;
105 }
106}
107
108<!doctype html>
109<html lang="en">
110<head>
111 <meta charset="utf-8"/>
112 <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
113 <title>Demo</title>
114 <meta name="description" content=""/>
115 <meta name="viewport" content="width=device-width"/>
116 <base href="/"/>
117 <link rel="stylesheet" type="text/css"
118 href="/webjars/bootstrap/css/bootstrap.min.css"/>
119 <script type="text/javascript" src="/webjars/jquery/jquery.min.js"></script>
120 <script type="text/javascript"
121 src="/webjars/bootstrap/js/bootstrap.min.js"></script>
122</head>
123<body>
124<h1>Login</h1>
125<div class="container unauthenticated">
126 With Facebook: <a href="/login/facebook">click here</a>
127</div>
128<div class="container authenticated" style="display: none">
129 Logged in as: <span id="user"></span>
130 <div>
131 <button onClick="logout()" class="btn btn-primary">Logout</button>
132 </div>
133</div>
134<script type="text/javascript"
135 src="/webjars/js-cookie/js.cookie.js"></script>
136<script type="text/javascript">
137 $.ajaxSetup({
138 beforeSend: function (xhr, settings) {
139 if (settings.type == 'POST' || settings.type == 'PUT'
140 || settings.type == 'DELETE') {
141 if (!(/^http:.*/.test(settings.url) || /^https:.*/
142 .test(settings.url))) {
143 // Only send the token to relative URLs i.e. locally.
144 xhr.setRequestHeader("X-XSRF-TOKEN",
145 Cookies.get('XSRF-TOKEN'));
146 }
147 }
148 }
149 });
150 $.get("/user", function (data) {
151 $("#user").html(data.userAuthentication.details.name);
152 $(".unauthenticated").hide();
153 $(".authenticated").show();
154 });
155 var logout = function () {
156 $.post("/logout", function () {
157 $("#user").html('');
158 $(".unauthenticated").show();
159 $(".authenticated").hide();
160 });
161 return true;
162 }
163</script>
164</body>
165</html>
166
167server:
168 port: 8080
169security:
170 oauth2:
171 client:
172 client-id: acme
173 client-secret: acmesecret
174 scope: read,write
175 auto-approve-scopes: '.*'
176
177facebook:
178 client:
179 clientId: 233668646673605
180 clientSecret: 33b17e044ee6a4fa383f46ec6e28ea1d
181 accessTokenUri: https://graph.facebook.com/oauth/access_token
182 userAuthorizationUri: https://www.facebook.com/dialog/oauth
183 tokenName: oauth_token
184 authenticationScheme: query
185 clientAuthenticationScheme: form
186 resource:
187 userInfoUri: https://graph.facebook.com/me
188github:
189 client:
190 clientId: bd1c0a783ccdd1c9b9e4
191 clientSecret: 1a9030fbca47a5b2c28e92f19050bb77824b5ad1
192 accessTokenUri: https://github.com/login/oauth/access_token
193 userAuthorizationUri: https://github.com/login/oauth/authorize
194 clientAuthenticationScheme: form
195 resource:
196 userInfoUri: https://api.github.com/user
197
198logging:
199 level:
200 org.springframework.security: DEBUG
201
202(index):44 Uncaught TypeError: Cannot read property 'details' of undefined
203 at Object.success ((index):44)
204 at j (jquery.js:3073)
205 at Object.fireWith [as resolveWith] (jquery.js:3185)
206 at x (jquery.js:8251)
207 at XMLHttpRequest.<anonymous> (jquery.js:8598)
208
209$.get("/user", function (data) {
210 $("#user").html(data.userAuthentication.details.name);
211 $(".unauthenticated").hide();
212 $(".authenticated").show();
213 });
214
215@RequestMapping("/user")
216public Principal user(Principal principal) {
217 return principal;
218}
219
220@RequestMapping({ "/user", "/me" })
221public Map<String, String> user(Principal principal) {
222 Map<String, String> map = new LinkedHashMap<>();
223 map.put("name", principal.getName());
224 return map;
225}
226
227$.get("/user", function(data) {
228 $("#user").html(data.userAuthentication.details.name);
229 $(".unauthenticated").hide();
230 $(".authenticated").show();
231});
232
233@RequestMapping({"/user", "/me"})
234public Map<String, Object> user(Principal principal) {
235 Map<String, Object> map = new LinkedHashMap<>();
236 map.put("name", principal.getName());
237 OAuth2Authentication user = (OAuth2Authentication) principal;
238 map.put("userAuthentication", new HashMap<String, Object>(){{
239 put("details", user.getUserAuthentication().getDetails());
240 }});
241 return map;
242}
243
244OAuth2ClientAuthenticationProcessingFilter facebookFilter = new OAuth2ClientAuthenticationProcessingFilter(
245 "/login/facebook");
246OAuth2RestTemplate facebookTemplate = new OAuth2RestTemplate(facebook(), oauth2ClientContext);
247facebookFilter.setRestTemplate(facebookTemplate);
248UserInfoTokenServices tokenServices = new UserInfoTokenServices(facebookResource().getUserInfoUri(),
249 facebook().getClientId());
250tokenServices.setRestTemplate(facebookTemplate);
251facebookFilter.setTokenServices(
252 new UserInfoTokenServices(facebookResource().getUserInfoUri(), facebook().getClientId()));
253return facebookFilter;
254
255private Filter ssoFilter(ClientResources client, String path) {
256 OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(
257 path);
258 OAuth2RestTemplate template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
259 filter.setRestTemplate(template);
260 UserInfoTokenServices tokenServices = new UserInfoTokenServices(
261 client.getResource().getUserInfoUri(), client.getClient().getClientId());
262 tokenServices.setRestTemplate(template);
263 filter.setTokenServices(tokenServices);
264 return filter;
265}
266
267(index):44 Uncaught TypeError: Cannot read property 'details' of undefined
268
269.anyRequest().authenticated().and().exceptionHandling()
270 .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/"))
271
272$("#user").html(data.userAuthentication.details.name);
273
274$("#user").html(data.name);
275
276server:
277 context-path: /client
278
279server:
280 servlet:
281 context-path: /client