· 7 years ago · Feb 02, 2018, 04:22 PM
1http://localhost:8082/app/helloworld
2
3http://localhost:8082/app/oauth/token?grant_type=password&client_id=restapp&client_secret=restapp&username=**USERNAME**&password=**PASSWORD**
4
5http://localhost:8082/app/helloworld/?access_token=**4855f557-c6ee-43b7-8617-c24591965206**
6
7BaseOAuth2ProtectedResourceDetails baseOAuth2ProtectedResourceDetails = new BaseOAuth2ProtectedResourceDetails();
8baseOAuth2ProtectedResourceDetails.setClientId("restapp");
9baseOAuth2ProtectedResourceDetails.setClientSecret("restapp");
10baseOAuth2ProtectedResourceDetails.setGrantType("password");
11// how to set user name and password ???
12
13DefaultAccessTokenRequest accessTokenRequest = new DefaultAccessTokenRequest();
14OAuth2ClientContext oAuth2ClientContext = new DefaultOAuth2ClientContext(accessTokenRequest());
15
16OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(baseOAuth2ProtectedResourceDetails,oAuth2ClientContext);
17
18@EnableOAuth2Client
19@Configuration
20class MyConfig{
21
22
23
24
25 @Value("${oauth.resource:http://localhost:8082}")
26 private String baseUrl;
27 @Value("${oauth.authorize:http://localhost:8082/oauth/authorize}")
28 private String authorizeUrl;
29 @Value("${oauth.token:http://localhost:8082/oauth/token}")
30 private String tokenUrl
31
32
33 @Bean
34 protected OAuth2ProtectedResourceDetails resource() {
35
36 ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
37
38 List scopes = new ArrayList<String>(2);
39 scopes.add("write");
40 scopes.add("read");
41 resource.setAccessTokenUri(tokenUrl);
42 resource.setClientId("restapp");
43 resource.setClientSecret("restapp");
44 resource.setGrantType("password");
45 resource.setScope(scopes);
46
47 resource.setUsername("**USERNAME**");
48 resource.setPassword("**PASSWORD**");
49
50 return resource;
51 }
52
53 @Bean
54 public OAuth2RestOperations restTemplate() {
55 AccessTokenRequest atr = new DefaultAccessTokenRequest();
56
57 return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
58 }
59
60}
61
62@Service
63@SuppressWarnings("unchecked")
64class MyService {
65 @Autowired
66 private OAuth2RestOperations restTemplate;
67
68 public MyService() {
69
70 restTemplate.getAccessToken();
71 }
72}
73
74security:
75 oauth2:
76 client:
77 clientId: 233668646673605
78 clientSecret: 33b17e044ee6a4fa383f46ec6e28ea1d
79 accessTokenUri: https://graph.facebook.com/oauth/access_token
80 userAuthorizationUri: https://www.facebook.com/dialog/oauth
81 tokenName: oauth_token
82 authenticationScheme: query
83 clientAuthenticationScheme: form
84 resource:
85 userInfoUri: https://graph.facebook.com/me
86
87@Component
88public class OAuthUser implements Serializable {
89
90private static final long serialVersionUID = 1L;
91
92private String authority;
93
94@JsonIgnore
95private String clientId;
96
97@JsonIgnore
98private String grantType;
99private boolean isAuthenticated;
100private Map<String, Object> userDetail = new LinkedHashMap<String, Object>();
101
102@JsonIgnore
103private String sessionId;
104
105@JsonIgnore
106private String tokenType;
107
108@JsonIgnore
109private String accessToken;
110
111@JsonIgnore
112private Principal principal;
113
114public void setOAuthUser(Principal principal) {
115 this.principal = principal;
116 init();
117}
118
119public Principal getPrincipal() {
120 return principal;
121}
122
123private void init() {
124 if (principal != null) {
125 OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) principal;
126 if (oAuth2Authentication != null) {
127 for (GrantedAuthority ga : oAuth2Authentication.getAuthorities()) {
128 setAuthority(ga.getAuthority());
129 }
130 setClientId(oAuth2Authentication.getOAuth2Request().getClientId());
131 setGrantType(oAuth2Authentication.getOAuth2Request().getGrantType());
132 setAuthenticated(oAuth2Authentication.getUserAuthentication().isAuthenticated());
133
134 OAuth2AuthenticationDetails oAuth2AuthenticationDetails = (OAuth2AuthenticationDetails) oAuth2Authentication
135 .getDetails();
136 if (oAuth2AuthenticationDetails != null) {
137 setSessionId(oAuth2AuthenticationDetails.getSessionId());
138 setTokenType(oAuth2AuthenticationDetails.getTokenType());
139
140 // This is what you will be looking for
141 setAccessToken(oAuth2AuthenticationDetails.getTokenValue());
142 }
143
144 // This detail is more related to Logged-in User
145 UsernamePasswordAuthenticationToken userAuthenticationToken = (UsernamePasswordAuthenticationToken) oAuth2Authentication.getUserAuthentication();
146 if (userAuthenticationToken != null) {
147 LinkedHashMap<String, Object> detailMap = (LinkedHashMap<String, Object>) userAuthenticationToken.getDetails();
148 if (detailMap != null) {
149 for (Map.Entry<String, Object> mapEntry : detailMap.entrySet()) {
150 //System.out.println("#### detail Key = " + mapEntry.getKey());
151 //System.out.println("#### detail Value = " + mapEntry.getValue());
152 getUserDetail().put(mapEntry.getKey(), mapEntry.getValue());
153 }
154
155 }
156
157 }
158
159 }
160
161 }
162}
163
164
165public String getAuthority() {
166 return authority;
167}
168
169public void setAuthority(String authority) {
170 this.authority = authority;
171}
172
173public String getClientId() {
174 return clientId;
175}
176
177public void setClientId(String clientId) {
178 this.clientId = clientId;
179}
180
181public String getGrantType() {
182 return grantType;
183}
184
185public void setGrantType(String grantType) {
186 this.grantType = grantType;
187}
188
189public boolean isAuthenticated() {
190 return isAuthenticated;
191}
192
193public void setAuthenticated(boolean isAuthenticated) {
194 this.isAuthenticated = isAuthenticated;
195}
196
197public Map<String, Object> getUserDetail() {
198 return userDetail;
199}
200
201public void setUserDetail(Map<String, Object> userDetail) {
202 this.userDetail = userDetail;
203}
204
205public String getSessionId() {
206 return sessionId;
207}
208
209public void setSessionId(String sessionId) {
210 this.sessionId = sessionId;
211}
212
213public String getTokenType() {
214 return tokenType;
215}
216
217public void setTokenType(String tokenType) {
218 this.tokenType = tokenType;
219}
220
221public String getAccessToken() {
222 return accessToken;
223}
224
225public void setAccessToken(String accessToken) {
226 this.accessToken = accessToken;
227}
228
229@Override
230public String toString() {
231 return "OAuthUser [clientId=" + clientId + ", grantType=" + grantType + ", isAuthenticated=" + isAuthenticated
232 + ", userDetail=" + userDetail + ", sessionId=" + sessionId + ", tokenType="
233 + tokenType + ", accessToken= " + accessToken + " ]";
234}
235
236@RestController
237public class YourController {
238
239@Autowired
240OAuthUser oAuthUser;
241
242// In case if you want to see Profile of user then you this
243@RequestMapping(value = "/profile", produces = MediaType.APPLICATION_JSON_VALUE)
244public OAuthUser user(Principal principal) {
245 oAuthUser.setOAuthUser(principal);
246
247 // System.out.println("#### Inside user() - oAuthUser.toString() = " + oAuthUser.toString());
248
249 return oAuthUser;
250}
251
252
253@RequestMapping(value = "/createOrder",
254 method = RequestMethod.POST,
255 headers = {"Content-type=application/json"},
256 consumes = MediaType.APPLICATION_JSON_VALUE,
257 produces = MediaType.APPLICATION_JSON_VALUE)
258public FinalOrderDetail createOrder(@RequestBody CreateOrder createOrder) {
259
260 return postCreateOrder_restTemplate(createOrder, oAuthUser).getBody();
261}
262
263
264private ResponseEntity<String> postCreateOrder_restTemplate(CreateOrder createOrder, OAuthUser oAuthUser) {
265
266String url_POST = "your post url goes here";
267
268 MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
269 headers.add("Authorization", String.format("%s %s", oAuthUser.getTokenType(), oAuthUser.getAccessToken()));
270 headers.add("Content-Type", "application/json");
271
272 RestTemplate restTemplate = new RestTemplate();
273 //restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
274
275 HttpEntity<String> request = new HttpEntity<String>(createOrder, headers);
276
277 ResponseEntity<String> result = restTemplate.exchange(url_POST, HttpMethod.POST, request, String.class);
278 System.out.println("#### post response = " + result);
279
280 return result;
281}
282
283
284}
285
286public ResourceOwnerPasswordResourceDetails() {
287 setGrantType("password");
288}
289
290@EnableOAuth2Client
291@Configuration
292class MyConfig {
293
294@Value("${security.oauth2.client.access-token-uri}")
295private String tokenUrl;
296
297@Value("${security.oauth2.client.client-id}")
298private String clientId;
299
300@Value("${security.oauth2.client.client-secret}")
301private String clientSecret;
302
303@Value("${security.oauth2.client.password-token}")
304private String passwordToken;
305
306@Value("${security.user.name}")
307private String username;
308
309@Value("${security.user.password}")
310private String password;
311
312
313@Bean
314protected OAuth2ProtectedResourceDetails resource() {
315
316 ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
317
318 resource.setAccessTokenUri(tokenUrl);
319 resource.setClientId(clientId);
320 resource.setClientSecret(clientSecret);
321 resource.setClientAuthenticationScheme(AuthenticationScheme.form);
322 resource.setUsername(username);
323 resource.setPassword(password + passwordToken);
324
325 return resource;
326}
327
328@Bean
329 public OAuth2RestOperations restTemplate() {
330 return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest()));
331 }
332}
333
334
335@Service
336@SuppressWarnings("unchecked")
337class MyService {
338 @Autowired
339 private OAuth2RestOperations restTemplate;
340
341 public MyService() {
342 restTemplate.getAccessToken();
343 }
344}