Skip to content

Commit f59e676

Browse files
committed
- refactors authentication interface to use URL instead of deeply tied request
1 parent 7542277 commit f59e676

11 files changed

Lines changed: 149 additions & 249 deletions

File tree

‎src/main/java/com/microsoft/graph/authentication/BaseAuthenticationProvider.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,15 @@
1010
/**
1111
* Provides basic common methods for all authentication providers
1212
*/
13-
public abstract class BaseAuthenticationProvider<T> implements IAuthenticationProvider<T> {
13+
public abstract class BaseAuthenticationProvider implements IAuthenticationProvider {
1414
private static final HashSet<String> validGraphHostNames = new HashSet<>(Arrays.asList("graph.microsoft.com", "graph.microsoft.us", "dod-graph.microsoft.us", "graph.microsoft.de", "microsoftgraph.chinacloudapi.cn"));
1515
/**
1616
* Determines whether a request should be authenticated or not based on it's url.
1717
* If you're implementing a custom provider, call that method first before getting the token
1818
* @param requestUrl request URL that is about to be executed
1919
* @return whether a token should be attached to this request
2020
*/
21-
protected boolean ShouldAuthenticateRequest(@Nonnull final URL requestUrl) {
21+
protected boolean shouldAuthenticateRequestWithUrl(@Nonnull final URL requestUrl) {
2222
if(requestUrl == null || !requestUrl.getProtocol().toLowerCase(Locale.ROOT).equals("https"))
2323
return false;
2424
final String hostName = requestUrl.getHost().toLowerCase(Locale.getDefault());
Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,20 @@
11
package com.microsoft.graph.authentication;
22

3-
import javax.annotation.Nonnull;
4-
5-
import com.microsoft.graph.exceptions.AuthenticationException;
6-
import com.microsoft.graph.http.IHttpRequest;
3+
import java.net.URL;
4+
import java.util.concurrent.CompletableFuture;
75

6+
import javax.annotation.Nonnull;
87

98
/**
109
* Authenticates requests to be sent to the API
11-
* @param <NativeRequestType> the type of the http native http request from the http client library
1210
*/
13-
public interface IAuthenticationProvider<NativeRequestType> {
14-
/**
15-
* Authenticates the request
16-
*
17-
* @param request the request to authenticate
18-
*/
19-
void authenticateRequest(@Nonnull final IHttpRequest request) throws AuthenticationException;
11+
public interface IAuthenticationProvider {
2012
/**
2113
* Authenticates the request
2214
*
23-
* @param request the request to authenticate
24-
* @return Request with Authorization header added to it
15+
* @param requestUrl the outgoing request URL
16+
* @return a future with the token
2517
*/
2618
@Nonnull
27-
NativeRequestType authenticateRequest(@Nonnull final NativeRequestType request) throws AuthenticationException;
19+
CompletableFuture<String> getAuthorizationTokenAsync(@Nonnull final URL requestUrl);
2820
}
Lines changed: 13 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,25 @@
11
package com.microsoft.graph.authentication;
22

3-
import com.azure.core.credential.AccessToken;
43
import com.azure.core.credential.TokenCredential;
54
import com.azure.core.credential.TokenRequestContext;
6-
import com.microsoft.graph.exceptions.AuthenticationException;
7-
import com.microsoft.graph.http.IHttpRequest;
8-
9-
import okhttp3.HttpUrl;
10-
import okhttp3.Request;
115

126
import java.net.URL;
13-
import java.time.Duration;
147
import java.util.Arrays;
158
import java.util.List;
9+
import java.util.concurrent.CompletableFuture;
1610

1711
import javax.annotation.Nonnull;
1812

1913
/**
2014
* An implementation of the Authentication Provider with Azure-identity
2115
*/
22-
public class TokenCredentialAuthProvider extends BaseAuthenticationProvider<Request> {
23-
/** The bearer value for the authorization request header, contains a space */
24-
protected static final String BEARER = "Bearer ";
25-
/** The authorization request header name */
26-
protected static final String AUTHORIZATION_HEADER = "Authorization";
27-
16+
public class TokenCredentialAuthProvider extends BaseAuthenticationProvider {
2817
/** TokenCredential expected from user */
2918
private final TokenCredential tokenCredential;
3019
/** Context options which can be optionally set by the user */
3120
private final TokenRequestContext context;
32-
/** maximum delay to wait for token obtention */
33-
private final Duration tokenBlockTimeout;
3421
/** Default scope to use when no scopes are provided */
3522
private static final String DEFAULT_GRAPH_SCOPE = "https://graph.microsoft.com/.default";
36-
/** Default timeout for token obtention, set to 10 minutes in case of interactive flows to give time to the end user */
37-
private static final long DEFAULT_TOKEN_TIMEOUT = 10;
3823
/**
3924
* Creates an Authentication provider using a passed in TokenCredential
4025
*
@@ -44,88 +29,38 @@ public TokenCredentialAuthProvider(@Nonnull final TokenCredential tokenCredentia
4429
this(Arrays.asList(new String[] {DEFAULT_GRAPH_SCOPE}), tokenCredential);
4530
}
4631

47-
/**
48-
* Creates an Authentication provider using a TokenCredential and list of scopes with default timeout (10 minutes)
49-
*
50-
* @param tokenCredential Credential object inheriting the TokenCredential interface used to instantiate the Auth Provider
51-
* @param scopes Specified desired scopes of the Auth Provider
52-
*/
53-
public TokenCredentialAuthProvider(@Nonnull final List<String> scopes, @Nonnull final TokenCredential tokenCredential) {
54-
this(scopes, Duration.ofMinutes(DEFAULT_TOKEN_TIMEOUT), tokenCredential);
55-
}
56-
5732
/**
5833
* Creates an Authentication provider using a TokenCredential and list of scopes
5934
*
6035
* @param tokenCredential Credential object inheriting the TokenCredential interface used to instantiate the Auth Provider
6136
* @param scopes Specified desired scopes of the Auth Provider
62-
* @param tokenObtentionTimeout Maximum time to wait for token obtention. Default 10 minutes. Use lower value on application with stable connectivity and no user interactions.
6337
*/
64-
public TokenCredentialAuthProvider(@Nonnull final List<String> scopes, @Nonnull final Duration tokenObtentionTimeout, @Nonnull final TokenCredential tokenCredential) {
38+
public TokenCredentialAuthProvider(@Nonnull final List<String> scopes, @Nonnull final TokenCredential tokenCredential) {
6539
if(tokenCredential == null) {
6640
throw new IllegalArgumentException("tokenCredential parameter cannot be null.");
6741
}
68-
if(tokenObtentionTimeout == null) {
69-
throw new IllegalArgumentException("tokenObtentionTimout parameter cannot be null");
70-
}
7142
if(scopes == null || scopes.isEmpty()) {
7243
throw new IllegalArgumentException("scopes parameter cannot be null or empty");
7344
}
7445
this.context = new TokenRequestContext();
7546
this.context.setScopes(scopes);
7647
this.tokenCredential = tokenCredential;
77-
this.tokenBlockTimeout = tokenObtentionTimeout;
78-
}
79-
80-
/**
81-
* Authenticates the request
82-
*
83-
* @param request the request to authenticate
84-
*/
85-
@Override
86-
public void authenticateRequest(@Nonnull final IHttpRequest request) throws AuthenticationException {
87-
if(request == null) {
88-
throw new IllegalArgumentException("request parameter cannot be null.");
89-
}
90-
final URL requestUrl = request.getRequestUrl();
91-
if(requestUrl != null && ShouldAuthenticateRequest(requestUrl)) {
92-
request.addHeader(AUTHORIZATION_HEADER, BEARER + getAccessToken());
93-
}
94-
}
95-
96-
/**
97-
* Authenticates the request
98-
*
99-
* @param request the request to authenticate
100-
* @return Request with Authorization header added to it
101-
*/
102-
@Override
103-
@Nonnull
104-
public Request authenticateRequest(@Nonnull final Request request) throws AuthenticationException {
105-
if(request == null) {
106-
throw new IllegalArgumentException("request parameter cannot be null.");
107-
}
108-
final HttpUrl requestUrl = request.url();
109-
if(requestUrl != null && ShouldAuthenticateRequest(requestUrl.url())) {
110-
return request.newBuilder()
111-
.addHeader(AUTHORIZATION_HEADER, BEARER + getAccessToken())
112-
.build();
113-
} else {
114-
return request;
115-
}
11648
}
11749

11850
/**
11951
* Returns an AccessToken as a string
12052
*
12153
* @return String representing the retrieved AccessToken
12254
*/
123-
private String getAccessToken() throws AuthenticationException {
124-
try {
125-
final AccessToken token = this.tokenCredential.getToken(this.context).block(this.tokenBlockTimeout);
126-
return token.getToken();
127-
} catch (RuntimeException e) {
128-
throw new AuthenticationException("Authentication failed or timed out.", e);
129-
}
55+
public CompletableFuture<String> getAuthorizationTokenAsync(@Nonnull final URL requestUrl) {
56+
if(requestUrl == null)
57+
throw new IllegalArgumentException("requestUrl parameter cannot be null");
58+
else if(shouldAuthenticateRequestWithUrl(requestUrl))
59+
return this.tokenCredential
60+
.getToken(this.context)
61+
.toFuture()
62+
.thenApply(resp -> resp.getToken());
63+
else
64+
return CompletableFuture.completedFuture((String)null);
13065
}
13166
}

‎src/main/java/com/microsoft/graph/core/BaseClient.java‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -119,9 +119,9 @@ public static class Builder<httpClientType, httpRequestType> {
119119
private IHttpProvider httpProvider;
120120
private ILogger logger;
121121
private httpClientType httpClient;
122-
private IAuthenticationProvider<httpRequestType> auth;
122+
private IAuthenticationProvider auth;
123123

124-
private IAuthenticationProvider<httpRequestType> getAuthenticationProvider() {
124+
private IAuthenticationProvider getAuthenticationProvider() {
125125
if(auth == null) {
126126
throw new NullPointerException("auth");
127127
} else {
@@ -142,10 +142,9 @@ private ISerializer getSerializer() {
142142
return serializer;
143143
}
144144
}
145-
@SuppressWarnings("unchecked")
146145
private httpClientType getHttpClient() {
147146
if(httpClient == null) {
148-
return (httpClientType)HttpClients.createDefault((IAuthenticationProvider<Request>)getAuthenticationProvider());
147+
return (httpClientType)HttpClients.createDefault(getAuthenticationProvider());
149148
} else {
150149
return httpClient;
151150
}
@@ -221,7 +220,7 @@ public Builder<httpClientType, httpRequestType> httpClient(@Nonnull final httpCl
221220
* @return the instance of this builder
222221
*/
223222
@Nonnull
224-
public Builder<httpClientType, httpRequestType> authenticationProvider(@Nonnull final IAuthenticationProvider<httpRequestType> auth) {
223+
public Builder<httpClientType, httpRequestType> authenticationProvider(@Nonnull final IAuthenticationProvider auth) {
225224
checkNotNull(auth, "auth");
226225
this.auth = auth;
227226
return this;

‎src/main/java/com/microsoft/graph/exceptions/AuthenticationException.java‎

Lines changed: 0 additions & 33 deletions
This file was deleted.

‎src/main/java/com/microsoft/graph/httpcore/AuthenticationHandler.java‎

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
package com.microsoft.graph.httpcore;
22

33
import java.io.IOException;
4+
import java.util.concurrent.CompletableFuture;
5+
import java.util.concurrent.ExecutionException;
46

57
import com.microsoft.graph.authentication.IAuthenticationProvider;
6-
import com.microsoft.graph.exceptions.AuthenticationException;
78

89
import javax.annotation.Nullable;
910
import javax.annotation.Nonnull;
@@ -19,19 +20,22 @@
1920
* Interceptor responsible for injecting the token in the request headers
2021
*/
2122
public class AuthenticationHandler implements Interceptor {
22-
23+
/** The bearer value for the authorization request header, contains a space */
24+
protected static final String BEARER = "Bearer ";
25+
/** The authorization request header name */
26+
protected static final String AUTHORIZATION_HEADER = "Authorization";
2327
/**
2428
* The current middleware type
2529
*/
2630
public final MiddlewareType MIDDLEWARE_TYPE = MiddlewareType.AUTHENTICATION;
2731

28-
private IAuthenticationProvider<Request> authProvider;
32+
private IAuthenticationProvider authProvider;
2933

3034
/**
3135
* Initialize a the handler with a authentication provider
3236
* @param authProvider the authentication provider to use
3337
*/
34-
public AuthenticationHandler(@Nonnull final IAuthenticationProvider<Request> authProvider) {
38+
public AuthenticationHandler(@Nonnull final IAuthenticationProvider authProvider) {
3539
this.authProvider = authProvider;
3640
}
3741

@@ -45,9 +49,19 @@ public Response intercept(@Nonnull final Chain chain) throws IOException {
4549
originalRequest.tag(TelemetryOptions.class).setFeatureUsage(TelemetryOptions.AUTH_HANDLER_ENABLED_FLAG);
4650

4751
try {
48-
final Request authenticatedRequest = authProvider.authenticateRequest(originalRequest);
49-
return authenticatedRequest == null ? chain.proceed(originalRequest) : chain.proceed(authenticatedRequest);
50-
} catch (AuthenticationException ex) {
52+
final CompletableFuture<String> future = authProvider.getAuthorizationTokenAsync(originalRequest.url().url());
53+
if(future == null)
54+
return chain.proceed(originalRequest);
55+
final String accessToken = future.get();
56+
if(accessToken == null)
57+
return chain.proceed(originalRequest);
58+
else {
59+
return chain.proceed(originalRequest
60+
.newBuilder()
61+
.addHeader(AUTHORIZATION_HEADER, BEARER + accessToken)
62+
.build());
63+
}
64+
} catch (InterruptedException | ExecutionException ex) {
5165
throw new IOException(ex);
5266
}
5367
}

‎src/main/java/com/microsoft/graph/httpcore/HttpClients.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ public static Builder custom() {
4343
* @return OkHttpClient build with authentication provider given, default redirect and default retry handlers
4444
*/
4545
@Nonnull
46-
public static OkHttpClient createDefault(@Nonnull final IAuthenticationProvider<Request> auth) {
46+
public static OkHttpClient createDefault(@Nonnull final IAuthenticationProvider auth) {
4747
return custom()
4848
.addInterceptor(new AuthenticationHandler(auth))
4949
.addInterceptor(new RetryHandler())

0 commit comments

Comments
 (0)