-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathOAuth2TwoLegged.java
More file actions
276 lines (237 loc) · 10.1 KB
/
OAuth2TwoLegged.java
File metadata and controls
276 lines (237 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/*
* Forge SDK
* The Forge Platform contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering.
*
* OpenAPI spec version: 0.1.0
* Contact: forge.help@autodesk.com
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.autodesk.client.auth;
import com.autodesk.client.Pair;
import com.autodesk.client.Configuration;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.joda.time.DateTime;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.IOException;
import java.util.*;
public class OAuth2TwoLegged implements Authentication {
private Credentials credentials;
private String name;
private String type;
private OAuthFlow flow;
private String tokenUrl;
private List<String> scopes;
private List<String> selectedScopes;
private String clientId;
private String clientSecret;
private Boolean autoRefresh;
// makes a POST request to url with form parameters and returns body as a string
private String post(String url, Map<String, String> formParameters, Map<String, String> headers)
throws ClientProtocolException, IOException {
HttpPost request = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (String key : headers.keySet()) {
request.setHeader(key, headers.get(key));
}
for (String key : formParameters.keySet()) {
nvps.add(new BasicNameValuePair(key, formParameters.get(key)));
}
request.setEntity(new UrlEncodedFormEntity(nvps));
return execute(request);
}
// makes request and checks response code for 200
private String execute(HttpRequestBase request) throws ClientProtocolException, IOException {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException(
"Expected 200 but got " + response.getStatusLine().getStatusCode() + ", with body " + body);
}
return body;
}
private String getScopes() {
String scopeStr = "";
if (!selectedScopes.isEmpty()) {
int index = 0;
for (String key : selectedScopes) {
index++;
if (scopes.contains(key)) {
scopeStr += key;
if (index < selectedScopes.size())
scopeStr += " ";
}
}
}
return scopeStr;
}
// validates that the selected scopes are not empty and also included in the
// list of all scopes.
private Boolean validateScopes(List<String> selectedScopes) throws Exception {
if (this.scopes.size() > 0) {
if (selectedScopes != null && selectedScopes.size() > 0) {
for (String key : selectedScopes) {
if (!this.scopes.contains(key)) {
throw new Exception(key + " scope is not allowed");
}
}
} else {
// throw if scope is null or undefined
throw new Exception("Scope is missing or empty, you must provide a valid scope");
}
} else {
throw new Exception("Authentication does not allow any scopes");
}
return true;
}
/**
* OAuth2TwoLegged Constructor
*
* @param clientId - the client id of the application
* @param clientSecret - the client secret of the application
* @param selectedScopes - the scope permissions used to generated access token
* @param autoRefresh - set autoRefresh to 'true' to automatically refresh
* the access token when it expires
* @throws Exception
*/
public OAuth2TwoLegged(String clientId, String clientSecret, List<String> selectedScopes, Boolean autoRefresh)
throws Exception {
this.flow = OAuthFlow.application;
this.scopes = new ArrayList<String>();
this.clientId = clientId;
this.clientSecret = clientSecret;
this.selectedScopes = selectedScopes;
this.autoRefresh = autoRefresh;
this.name = "oauth2_application";
this.type = "oauth2";
this.tokenUrl = Configuration.getDefaultApiClient().getBasePath() + "/authentication/v2/token";
this.scopes.add("data:read");
this.scopes.add("data:write");
this.scopes.add("data:create");
this.scopes.add("data:search");
this.scopes.add("bucket:create");
this.scopes.add("bucket:read");
this.scopes.add("bucket:update");
this.scopes.add("bucket:delete");
this.scopes.add("code:all");
this.scopes.add("account:read");
this.scopes.add("account:write");
this.scopes.add("user-profile:read");
this.scopes.add("viewables:read");
validateScopes(selectedScopes);
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
if (this.credentials != null && this.credentials.getAccessToken() != null) {
headerParams.put("Authorization", "Bearer " + this.credentials.getAccessToken());
}
}
@Override
public String getName() {
return name;
}
public void setSelectedScopes(List<String> selectedScopes) throws Exception {
if (validateScopes(selectedScopes)) {
this.selectedScopes = selectedScopes;
}
}
public Credentials getCredentials() {
return this.credentials;
}
public Boolean isAutoRefresh() {
return this.autoRefresh;
}
/**
* Get the access token in a 2-legged flow (updated to v2)
*
* @return
*/
public Credentials authenticate() throws Exception {
if (flow == OAuthFlow.application) {
final String url = this.tokenUrl;
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
headers.put("Accept", "application/json");
headers.put("Authorization", getAuthorizationString());
Map<String, String> body = new HashMap<>();
body.put("grant_type", "client_credentials");
String scopeStr = getScopes();
if (!scopeStr.isEmpty()) {
body.put("scope", scopeStr);
}
Credentials response = null;
try {
String bodyResponse = post(url, body, headers);
JSONObject jsonObject = null;
// get the access token from json
try {
jsonObject = (JSONObject) new JSONParser().parse(bodyResponse);
String access_token = (String) jsonObject.get("access_token");
// calculate "expires at"
long expires_in = (long) jsonObject.get("expires_in");
DateTime later = DateTime.now().plusSeconds((int) expires_in);
Long expiresAt = later.toDate().getTime();
// should we delete the last this.credentials?
this.credentials = new Credentials(access_token, expiresAt);
response = this.credentials;
// refresh token 3 minutes (3*60 seconds) in advance.
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// get token again
try {
authenticate();
} catch (Exception e) {
e.printStackTrace();
}
}
}, (expires_in - 3 * 60) * 1000);
} catch (ParseException e) {
throw new RuntimeException("Unable to parse json " + body);
}
} catch (IOException e) {
System.err.println("Exception when trying to get access token");
e.printStackTrace();
}
return response;
} else {
throw new Exception("getAccessToken requires application flow type");
}
}
private String getAuthorizationString() {
String encodedClientIdSecret = Base64.getEncoder().encodeToString((this.clientId + ":" + this.clientSecret).getBytes());
return "Basic " + encodedClientIdSecret;
}
public Boolean isAccessTokenExpired() {
return (this.credentials != null) && (this.credentials.getExpiresAt() <= (new Date().getTime()));
}
}