-
Notifications
You must be signed in to change notification settings - Fork 229
/
OAuth2Credentials.java
352 lines (311 loc) · 10.9 KB
/
OAuth2Credentials.java
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/*
* Copyright 2015, Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.google.auth.oauth2;
import com.google.api.client.util.Clock;
import com.google.auth.Credentials;
import com.google.auth.RequestMetadataCallback;
import com.google.auth.http.AuthHttpConstants;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.ServiceLoader;
import java.util.concurrent.Executor;
/** Base type for Credentials using OAuth2. */
public class OAuth2Credentials extends Credentials {
private static final long serialVersionUID = 4556936364828217687L;
private static final long MINIMUM_TOKEN_MILLISECONDS = 60000L * 5L;
// byte[] is serializable, so the lock variable can be final
private final Object lock = new byte[0];
private Map<String, List<String>> requestMetadata;
private AccessToken temporaryAccess;
// Change listeners are not serialized
private transient List<CredentialsChangedListener> changeListeners;
// Until we expose this to the users it can remain transient and non-serializable
@VisibleForTesting transient Clock clock = Clock.SYSTEM;
/**
* Returns the credentials instance from the given access token.
*
* @param accessToken the access token
* @return the credentials instance
*/
public static OAuth2Credentials create(AccessToken accessToken) {
return OAuth2Credentials.newBuilder().setAccessToken(accessToken).build();
}
/** Default constructor. */
protected OAuth2Credentials() {
this(null);
}
/**
* Constructor with explicit access token.
*
* @param accessToken initial or temporary access token
*/
protected OAuth2Credentials(AccessToken accessToken) {
if (accessToken != null) {
useAccessToken(accessToken);
}
}
@Override
public String getAuthenticationType() {
return "OAuth2";
}
@Override
public boolean hasRequestMetadata() {
return true;
}
@Override
public boolean hasRequestMetadataOnly() {
return true;
}
/**
* Returns the cached access token.
*
* <p>If not set, you should call {@link #refresh()} to fetch and cache an access token.
*
* @return The cached access token.
*/
public final AccessToken getAccessToken() {
return temporaryAccess;
}
@Override
public void getRequestMetadata(
final URI uri, Executor executor, final RequestMetadataCallback callback) {
Map<String, List<String>> metadata;
synchronized (lock) {
if (shouldRefresh()) {
// The base class implementation will do a blocking get in the executor.
super.getRequestMetadata(uri, executor, callback);
return;
}
metadata = Preconditions.checkNotNull(requestMetadata, "cached requestMetadata");
}
callback.onSuccess(metadata);
}
/**
* Provide the request metadata by ensuring there is a current access token and providing it as an
* authorization bearer token.
*/
@Override
public Map<String, List<String>> getRequestMetadata(URI uri) throws IOException {
synchronized (lock) {
if (shouldRefresh()) {
refresh();
}
return Preconditions.checkNotNull(requestMetadata, "requestMetadata");
}
}
/** Refresh the token by discarding the cached token and metadata and requesting the new ones. */
@Override
public void refresh() throws IOException {
synchronized (lock) {
requestMetadata = null;
temporaryAccess = null;
useAccessToken(Preconditions.checkNotNull(refreshAccessToken(), "new access token"));
if (changeListeners != null) {
for (CredentialsChangedListener listener : changeListeners) {
listener.onChanged(this);
}
}
}
}
/**
* Refresh these credentials only if they have expired or are expiring imminently.
*
* @throws IOException during token refresh.
*/
public void refreshIfExpired() throws IOException {
synchronized (lock) {
if (shouldRefresh()) {
refresh();
}
}
}
// Must be called under lock
private void useAccessToken(AccessToken token) {
this.temporaryAccess = token;
this.requestMetadata =
Collections.singletonMap(
AuthHttpConstants.AUTHORIZATION,
Collections.singletonList(OAuth2Utils.BEARER_PREFIX + token.getTokenValue()));
}
// Must be called under lock
// requestMetadata will never be null if false is returned.
private boolean shouldRefresh() {
Long expiresIn = getExpiresInMilliseconds();
return requestMetadata == null || expiresIn != null && expiresIn <= MINIMUM_TOKEN_MILLISECONDS;
}
/**
* Method to refresh the access token according to the specific type of credentials.
*
* <p>Throws IllegalStateException if not overridden since direct use of OAuth2Credentials is only
* for temporary or non-refreshing access tokens.
*
* @return Refreshed access token.
* @throws IOException from derived implementations
*/
public AccessToken refreshAccessToken() throws IOException {
throw new IllegalStateException(
"OAuth2Credentials instance does not support refreshing the"
+ " access token. An instance with a new access token should be used, or a derived type"
+ " that supports refreshing.");
}
/**
* Adds a listener that is notified when the Credentials data changes.
*
* <p>This is called when token content changes, such as when the access token is refreshed. This
* is typically used by code caching the access token.
*
* @param listener The listener to be added.
*/
public final void addChangeListener(CredentialsChangedListener listener) {
synchronized (lock) {
if (changeListeners == null) {
changeListeners = new ArrayList<>();
}
changeListeners.add(listener);
}
}
/**
* Removes a listener that was added previously.
*
* @param listener The listener to be removed.
*/
public final void removeChangeListener(CredentialsChangedListener listener) {
synchronized (lock) {
if (changeListeners != null) {
changeListeners.remove(listener);
}
}
}
/**
* Return the remaining time the current access token will be valid, or null if there is no token
* or expiry information. Must be called under lock.
*/
private Long getExpiresInMilliseconds() {
if (temporaryAccess == null) {
return null;
}
Date expirationTime = temporaryAccess.getExpirationTime();
if (expirationTime == null) {
return null;
}
return (expirationTime.getTime() - clock.currentTimeMillis());
}
/**
* Listener for changes to credentials.
*
* <p>This is called when token content changes, such as when the access token is refreshed. This
* is typically used by code caching the access token.
*/
public interface CredentialsChangedListener {
/**
* Notifies that the credentials have changed.
*
* <p>This is called when token content changes, such as when the access token is refreshed.
* This is typically used by code caching the access token.
*
* @param credentials The updated credentials instance
* @throws IOException My be thrown by listeners if saving credentials fails.
*/
void onChanged(OAuth2Credentials credentials) throws IOException;
}
@Override
public int hashCode() {
return Objects.hash(requestMetadata, temporaryAccess);
}
protected Map<String, List<String>> getRequestMetadataInternal() {
return requestMetadata;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("requestMetadata", requestMetadata)
.add("temporaryAccess", temporaryAccess)
.toString();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof OAuth2Credentials)) {
return false;
}
OAuth2Credentials other = (OAuth2Credentials) obj;
return Objects.equals(this.requestMetadata, other.requestMetadata)
&& Objects.equals(this.temporaryAccess, other.temporaryAccess);
}
private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
input.defaultReadObject();
clock = Clock.SYSTEM;
}
@SuppressWarnings("unchecked")
protected static <T> T newInstance(String className) throws IOException, ClassNotFoundException {
try {
return (T) Class.forName(className).newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new IOException(e);
}
}
protected static <T> T getFromServiceLoader(Class<? extends T> clazz, T defaultInstance) {
return Iterables.getFirst(ServiceLoader.load(clazz), defaultInstance);
}
public static Builder newBuilder() {
return new Builder();
}
public Builder toBuilder() {
return new Builder(this);
}
public static class Builder {
private AccessToken accessToken;
protected Builder() {}
protected Builder(OAuth2Credentials credentials) {
this.accessToken = credentials.getAccessToken();
}
public Builder setAccessToken(AccessToken token) {
this.accessToken = token;
return this;
}
public AccessToken getAccessToken() {
return accessToken;
}
public OAuth2Credentials build() {
return new OAuth2Credentials(accessToken);
}
}
}