Skip to content

Commit d778a72

Browse files
authored
Merge pull request microsoft#51 from Microsoft/fix-intercept
Cleanup OAuth, use clean interceptor pattern
2 parents 84eaf51 + 936b7c7 commit d778a72

4 files changed

Lines changed: 201 additions & 231 deletions

File tree

libraries/bot-connector/src/main/java/com/microsoft/bot/connector/authentication/MicrosoftAppCredentials.java

Lines changed: 0 additions & 131 deletions
Original file line numberDiff line numberDiff line change
@@ -91,59 +91,7 @@ public String getToken(Request request) throws IOException {
9191
}
9292
return this.currentToken;
9393
}
94-
public CompletableFuture<String> GetTokenAsync() throws IOException, URISyntaxException {
95-
return this.GetTokenAsync(false);
96-
}
97-
98-
/**
99-
* Apply the credentials to the HTTP request.
100-
* @param request The HTTP request.
101-
*/
102-
public CompletableFuture<Response> ProcessHttpRequestAsync(boolean applyCredentials, String httpVerb, String url) throws InvalidParameterException, IOException, URISyntaxException {
103-
return ProcessHttpRequestAsync(applyCredentials, httpVerb, url, null);
104-
}
105-
public CompletableFuture<Response> ProcessHttpRequestAsync(boolean applyCredentials, String httpVerb, String url, RequestBody body) throws InvalidParameterException, IOException, URISyntaxException {
106-
Request.Builder httpRequestBuilder = new Request.Builder();
107-
switch (httpVerb.toLowerCase()) {
108-
case "get":
109-
httpRequestBuilder.get();
110-
break;
111-
case "post":
112-
if (body == null)
113-
throw new InvalidParameterException("Attempting to POST with no body provided");
114-
httpRequestBuilder.post(body);
115-
break;
116-
case "delete":
117-
if (body == null)
118-
httpRequestBuilder.delete();
119-
else
120-
httpRequestBuilder.delete(body);
121-
break;
12294

123-
default:
124-
throw new InvalidParameterException(String.format("Do not support %s http verb yet", httpVerb));
125-
126-
}
127-
httpRequestBuilder.url(url);
128-
129-
// Resolve the token if required
130-
if (ShouldSetToken(url))
131-
httpRequestBuilder.addHeader("Authorization", await(GetTokenAsync()));
132-
133-
Request request = httpRequestBuilder.build();
134-
135-
// Convert to CompletableFuture
136-
OkHttpClient client = this.client;
137-
if (applyCredentials) {
138-
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
139-
this.applyCredentialsFilter(clientBuilder);
140-
client = clientBuilder.build();
141-
}
142-
Call call = client.newCall(request);
143-
ResponseFuture result = new ResponseFuture(call);
144-
call.enqueue(result);
145-
return result.future;
146-
}
14795

14896

14997
private boolean ShouldSetToken(String url)
@@ -157,85 +105,6 @@ private boolean ShouldSetToken(String url)
157105

158106

159107

160-
public CompletableFuture<String> GetTokenAsync(boolean forceRefresh) throws IOException, URISyntaxException {
161-
if (forceRefresh == false) {
162-
// check the global cache for the token. If we have it, and it's valid, we're done.
163-
OAuthResponse oAuthToken = null;
164-
boolean found = false;
165-
synchronized (this.cacheSync) {
166-
if (this.cache.containsKey(this.getTokenCacheKey())) {
167-
oAuthToken = this.cache.get(this.getTokenCacheKey());
168-
found = true;
169-
}
170-
}
171-
// we have the token. Is it valid?
172-
if (found && oAuthToken.getExpirationTime().getMillis() > DateTime.now(DateTimeZone.UTC).getMillis())
173-
{
174-
return completedFuture(oAuthToken.getAccessToken());
175-
}
176-
}
177-
// We need to refresh the token, because:
178-
// 1. The user requested it via the forceRefresh parameter
179-
// 2. We have it, but it's expired
180-
// 3. We don't have it in the cache.
181-
182-
OAuthResponse token = await(this.RefreshTokenAsync());
183-
synchronized (cacheSync)
184-
{
185-
this.cache.put(getTokenCacheKey(), token);
186-
}
187-
188-
return completedFuture(token.getAccessToken());
189-
}
190-
191-
private CompletableFuture<Response> PostAsync(String endpoint, HashMap<String, String> content) throws JsonProcessingException, URISyntaxException {
192-
String bodyText = this.mapper.writeValueAsString(content);
193-
194-
RequestBody body = RequestBody.create(this.FORM_ENCODE, this.MakeFormBody(content));
195-
Request request = new Request.Builder()
196-
.url(endpoint)
197-
.post(body)
198-
.build();
199-
Call call = client.newCall(request);
200-
ResponseFuture result = new ResponseFuture(call);
201-
call.enqueue(result);
202-
return result.future;
203-
}
204-
private String MakeFormBody(HashMap<String, String> values) throws URISyntaxException, JsonProcessingException {
205-
String formBody = values.keySet().stream()
206-
.map(key -> {
207-
try {
208-
return key + "=" + URLEncoder.encode(values.get(key), StandardCharsets.UTF_8.toString());
209-
} catch (UnsupportedEncodingException e) {
210-
throw new RuntimeException(e);
211-
}
212-
})
213-
.collect(joining("&", "", ""));
214-
return formBody;
215-
}
216-
217-
// Corresponds to https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-connector-authentication?view=azure-bot-service-4.0
218-
// Step 1: Request an access token from the MSA/AAD v2 login service
219-
private CompletableFuture<OAuthResponse> RefreshTokenAsync() throws IOException, URISyntaxException {
220-
HashMap<String, String> content = new HashMap<String, String>();
221-
content.put("grant_type", "client_credentials");
222-
content.put("client_id", (this.appId==null) ? "" : this.appId);
223-
content.put("client_secret", (this.appPassword==null) ? "" : this.appPassword );
224-
content.put("scope", this.OAuthScope);
225-
226-
try (Response response = await(this.PostAsync(this.OAuthEndpoint, content)))
227-
{
228-
ResponseBody body = null;
229-
if (response.code() < 200 || response.code() >= 300 )
230-
throw new IOException(String.format("Bad response : %s", response.code()) );
231-
body = response.body();
232-
OAuthResponse oauthresponse = this.mapper.readValue(body.string(), OAuthResponse.class);
233-
DateTime modifiedExpiration = DateTime.now(DateTimeZone.UTC).plusSeconds(oauthresponse.getExpiresIn()).minusSeconds(60);
234-
oauthresponse.withExpirationTime(modifiedExpiration);
235-
return completedFuture(oauthresponse);
236-
}
237-
}
238-
239108
@Override
240109
public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) {
241110
clientBuilder.interceptors().add(new MicrosoftAppCredentialsInterceptor(this));

0 commit comments

Comments
 (0)