-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathStsRequestHandler.java
More file actions
240 lines (213 loc) · 9.79 KB
/
StsRequestHandler.java
File metadata and controls
240 lines (213 loc) · 9.79 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
/*
* Copyright 2021 Google LLC
*
* 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 LLC 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.http.GenericUrl;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.UrlEncodedContent;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.JsonParser;
import com.google.api.client.util.GenericData;
import com.google.common.base.Joiner;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Nullable;
/**
* Implements the OAuth 2.0 token exchange based on <a
* href="https://tools.ietf.org/html/rfc8693">RFC 8693</a>.
*
* <p>This class handles the process of exchanging one type of token for another using the Security
* Token Service (STS). It constructs and sends the token exchange request to the STS endpoint and
* parses the response to create an {@link StsTokenExchangeResponse} object.
*
* <p>Use the {@link #newBuilder(String, StsTokenExchangeRequest, HttpRequestFactory)} method to
* create a new builder for constructing an instance of this class.
*/
public final class StsRequestHandler {
private static final LoggerProvider LOGGER_PROVIDER =
LoggerProvider.forClazz(StsRequestHandler.class);
private static final String TOKEN_EXCHANGE_GRANT_TYPE =
"urn:ietf:params:oauth:grant-type:token-exchange";
private static final String PARSE_ERROR_PREFIX = "Error parsing token response.";
private final String tokenExchangeEndpoint;
private final StsTokenExchangeRequest request;
private final HttpRequestFactory httpRequestFactory;
@Nullable private final HttpHeaders headers;
@Nullable private final String internalOptions;
private StsRequestHandler(Builder builder) {
this.tokenExchangeEndpoint = builder.tokenExchangeEndpoint;
this.request = builder.request;
this.httpRequestFactory = builder.httpRequestFactory;
this.headers = builder.headers;
this.internalOptions = builder.internalOptions;
}
/**
* Returns a new builder for creating an instance of {@link StsRequestHandler}.
*
* @param tokenExchangeEndpoint The STS token exchange endpoint.
* @param stsTokenExchangeRequest The STS token exchange request.
* @param httpRequestFactory The HTTP request factory to use for sending the request.
* @return A new builder instance.
*/
public static Builder newBuilder(
String tokenExchangeEndpoint,
StsTokenExchangeRequest stsTokenExchangeRequest,
HttpRequestFactory httpRequestFactory) {
return new Builder(tokenExchangeEndpoint, stsTokenExchangeRequest, httpRequestFactory);
}
/** Exchanges the provided token for another type of token based on the RFC 8693 spec. */
public StsTokenExchangeResponse exchangeToken() throws IOException {
UrlEncodedContent content = new UrlEncodedContent(buildTokenRequest());
HttpRequest httpRequest =
httpRequestFactory.buildPostRequest(new GenericUrl(tokenExchangeEndpoint), content);
// Disable automatic logging by HttpRequest from google-http-java-client to prevent leakage
// of sensitive tokens. Google Http Java Client will log if logging is enabled (default on)
// and if the log level is set to `CONFIG`. Logging via LoggingUtils
// is used instead to mask those tokens.
httpRequest.setLoggingEnabled(false);
httpRequest.setParser(new JsonObjectParser(OAuth2Utils.JSON_FACTORY));
if (headers != null) {
httpRequest.setHeaders(headers);
}
try {
LoggingUtils.logRequest(httpRequest, LOGGER_PROVIDER, "Sending request for token exchange");
HttpResponse response = httpRequest.execute();
LoggingUtils.logResponse(response, LOGGER_PROVIDER, "Received response for token exchange");
GenericData responseData = response.parseAs(GenericData.class);
LoggingUtils.logResponsePayload(
responseData, LOGGER_PROVIDER, "Response payload for token exchange");
return buildResponse(responseData);
} catch (HttpResponseException e) {
throw OAuthException.createFromHttpResponseException(e);
}
}
private GenericData buildTokenRequest() {
GenericData tokenRequest =
new GenericData()
.set("grant_type", TOKEN_EXCHANGE_GRANT_TYPE)
.set("subject_token_type", request.getSubjectTokenType())
.set("subject_token", request.getSubjectToken());
// Add scopes as a space-delimited string.
List<String> scopes = new ArrayList<>();
if (request.hasScopes()) {
scopes.addAll(request.getScopes());
tokenRequest.set("scope", Joiner.on(' ').join(scopes));
}
// Set the requested token type, which defaults to
// urn:ietf:params:oauth:token-type:access_token.
String requestTokenType =
request.hasRequestedTokenType()
? request.getRequestedTokenType()
: OAuth2Utils.TOKEN_TYPE_ACCESS_TOKEN;
tokenRequest.set("requested_token_type", requestTokenType);
// Add other optional params, if possible.
if (request.hasResource()) {
tokenRequest.set("resource", request.getResource());
}
if (request.hasAudience()) {
tokenRequest.set("audience", request.getAudience());
}
if (request.hasActingParty()) {
tokenRequest.set("actor_token", request.getActingParty().getActorToken());
tokenRequest.set("actor_token_type", request.getActingParty().getActorTokenType());
}
if (internalOptions != null && !internalOptions.isEmpty()) {
tokenRequest.set("options", internalOptions);
}
return tokenRequest;
}
private StsTokenExchangeResponse buildResponse(GenericData responseData) throws IOException {
String accessToken =
OAuth2Utils.validateString(responseData, "access_token", PARSE_ERROR_PREFIX);
String issuedTokenType =
OAuth2Utils.validateString(responseData, "issued_token_type", PARSE_ERROR_PREFIX);
String tokenType = OAuth2Utils.validateString(responseData, "token_type", PARSE_ERROR_PREFIX);
StsTokenExchangeResponse.Builder builder =
StsTokenExchangeResponse.newBuilder(accessToken, issuedTokenType, tokenType);
if (responseData.containsKey("expires_in")) {
builder.setExpiresInSeconds(
OAuth2Utils.validateLong(responseData, "expires_in", PARSE_ERROR_PREFIX));
}
if (responseData.containsKey("refresh_token")) {
builder.setRefreshToken(
OAuth2Utils.validateString(responseData, "refresh_token", PARSE_ERROR_PREFIX));
}
if (responseData.containsKey("scope")) {
String scope = OAuth2Utils.validateString(responseData, "scope", PARSE_ERROR_PREFIX);
builder.setScopes(Arrays.asList(scope.trim().split("\\s+")));
}
if (responseData.containsKey("access_boundary_session_key")) {
builder.setAccessBoundarySessionKey(
OAuth2Utils.validateString(
responseData, "access_boundary_session_key", PARSE_ERROR_PREFIX));
}
return builder.build();
}
private GenericJson parseJson(String json) throws IOException {
JsonParser parser = OAuth2Utils.JSON_FACTORY.createJsonParser(json);
return parser.parseAndClose(GenericJson.class);
}
public static class Builder {
private final String tokenExchangeEndpoint;
private final StsTokenExchangeRequest request;
private final HttpRequestFactory httpRequestFactory;
@Nullable private HttpHeaders headers;
@Nullable private String internalOptions;
private Builder(
String tokenExchangeEndpoint,
StsTokenExchangeRequest stsTokenExchangeRequest,
HttpRequestFactory httpRequestFactory) {
this.tokenExchangeEndpoint = tokenExchangeEndpoint;
this.request = stsTokenExchangeRequest;
this.httpRequestFactory = httpRequestFactory;
}
@CanIgnoreReturnValue
public StsRequestHandler.Builder setHeaders(HttpHeaders headers) {
this.headers = headers;
return this;
}
@CanIgnoreReturnValue
public StsRequestHandler.Builder setInternalOptions(String internalOptions) {
this.internalOptions = internalOptions;
return this;
}
public StsRequestHandler build() {
return new StsRequestHandler(this);
}
}
}