/
LocalServerReceiver.java
297 lines (255 loc) · 8.63 KB
/
LocalServerReceiver.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
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.extensions.jetty.auth.oauth2;
import com.google.api.client.extensions.java6.auth.oauth2.VerificationCodeReceiver;
import com.google.api.client.util.Throwables;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.Semaphore;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
/**
* OAuth 2.0 verification code receiver that runs a Jetty server on a free port, waiting for a
* redirect with the verification code.
*
* <p>
* Implementation is thread-safe.
* </p>
*
* @since 1.11
* @author Yaniv Inbar
*/
public final class LocalServerReceiver implements VerificationCodeReceiver {
private static final String LOCALHOST = "localhost";
private static final String CALLBACK_PATH = "/Callback";
/** Server or {@code null} before {@link #getRedirectUri()}. */
private Server server;
/** Verification code or {@code null} for none. */
String code;
/** Error code or {@code null} for none. */
String error;
/** To block until receiving an authorization response or stop() is called. */
final Semaphore waitUnlessSignaled = new Semaphore(0 /* initially zero permit */);
/** Port to use or {@code -1} to select an unused port in {@link #getRedirectUri()}. */
private int port;
/** Host name to use. */
private final String host;
/** Callback path of redirect_uri */
private final String callbackPath;
/**
* URL to an HTML page to be shown (via redirect) after successful login. If null, a canned
* default landing page will be shown (via direct response).
*/
private String successLandingPageUrl;
/**
* URL to an HTML page to be shown (via redirect) after failed login. If null, a canned
* default landing page will be shown (via direct response).
*/
private String failureLandingPageUrl;
/**
* Constructor that starts the server on {@link #LOCALHOST} and an unused port.
*
* <p>
* Use {@link Builder} if you need to specify any of the optional parameters.
* </p>
*/
public LocalServerReceiver() {
this(LOCALHOST, -1, CALLBACK_PATH, null, null);
}
/**
* Constructor.
*
* @param host Host name to use
* @param port Port to use or {@code -1} to select an unused port
*/
LocalServerReceiver(String host, int port,
String successLandingPageUrl, String failureLandingPageUrl) {
this(host, port, CALLBACK_PATH, successLandingPageUrl, failureLandingPageUrl);
}
/**
* Constructor.
*
* @param host Host name to use
* @param port Port to use or {@code -1} to select an unused port
*/
LocalServerReceiver(String host, int port, String callbackPath,
String successLandingPageUrl, String failureLandingPageUrl) {
this.host = host;
this.port = port;
this.callbackPath = callbackPath;
this.successLandingPageUrl = successLandingPageUrl;
this.failureLandingPageUrl = failureLandingPageUrl;
}
@Override
public String getRedirectUri() throws IOException {
server = new Server(port != -1 ? port : 0);
Connector connector = server.getConnectors()[0];
connector.setHost(host);
server.setHandler(new CallbackHandler());
try {
server.start();
port = connector.getLocalPort();
} catch (Exception e) {
Throwables.propagateIfPossible(e);
throw new IOException(e);
}
return "http://" + connector.getHost() + ":" + port + callbackPath;
}
/**
* Blocks until the server receives a login result, or the server is stopped
* by {@link #stop()}, to return an authorization code.
*
* @return authorization code if login succeeds; may return {@code null} if the server
* is stopped by {@link #stop()}
* @throws IOException if the server receives an error code (through an HTTP request
* parameter {@code error})
*/
@Override
public String waitForCode() throws IOException {
waitUnlessSignaled.acquireUninterruptibly();
if (error != null) {
throw new IOException("User authorization failed (" + error + ")");
}
return code;
}
@Override
public void stop() throws IOException {
waitUnlessSignaled.release();
if (server != null) {
try {
server.stop();
} catch (Exception e) {
Throwables.propagateIfPossible(e);
throw new IOException(e);
}
server = null;
}
}
/** Returns the host name to use. */
public String getHost() {
return host;
}
/**
* Returns the port to use or {@code -1} to select an unused port in {@link #getRedirectUri()}.
*/
public int getPort() {
return port;
}
/**
* Returns callback path used in redirect_uri.
*/
public String getCallbackPath() {
return callbackPath;
}
/**
* Builder.
*
* <p>
* Implementation is not thread-safe.
* </p>
*/
public static final class Builder {
/** Host name to use. */
private String host = LOCALHOST;
/** Port to use or {@code -1} to select an unused port. */
private int port = -1;
private String successLandingPageUrl;
private String failureLandingPageUrl;
private String callbackPath = CALLBACK_PATH;
/** Builds the {@link LocalServerReceiver}. */
public LocalServerReceiver build() {
return new LocalServerReceiver(host, port, callbackPath,
successLandingPageUrl, failureLandingPageUrl);
}
/** Returns the host name to use. */
public String getHost() {
return host;
}
/** Sets the host name to use. */
public Builder setHost(String host) {
this.host = host;
return this;
}
/** Returns the port to use or {@code -1} to select an unused port. */
public int getPort() {
return port;
}
/** Sets the port to use or {@code -1} to select an unused port. */
public Builder setPort(int port) {
this.port = port;
return this;
}
/** Returns the callback path of redirect_uri */
public String getCallbackPath() {
return callbackPath;
}
/** Set the callback path of redirect_uri */
public Builder setCallbackPath(String callbackPath) {
this.callbackPath = callbackPath;
return this;
}
public Builder setLandingPages(String successLandingPageUrl, String failureLandingPageUrl) {
this.successLandingPageUrl = successLandingPageUrl;
this.failureLandingPageUrl = failureLandingPageUrl;
return this;
}
}
/**
* Jetty handler that takes the verifier token passed over from the OAuth provider and stashes it
* where {@link #waitForCode} will find it.
*/
class CallbackHandler extends AbstractHandler {
@Override
public void handle(
String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response
)
throws IOException {
if (!callbackPath.equals(target)) {
return;
}
try {
((Request) request).setHandled(true);
error = request.getParameter("error");
code = request.getParameter("code");
if (error == null && successLandingPageUrl != null) {
response.sendRedirect(successLandingPageUrl);
} else if (error != null && failureLandingPageUrl != null) {
response.sendRedirect(failureLandingPageUrl);
} else {
writeLandingHtml(response);
}
response.flushBuffer();
}
finally {
waitUnlessSignaled.release();
}
}
private void writeLandingHtml(HttpServletResponse response) throws IOException {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/html");
PrintWriter doc = response.getWriter();
doc.println("<html>");
doc.println("<head><title>OAuth 2.0 Authentication Token Received</title></head>");
doc.println("<body>");
doc.println("Received verification code. You may now close this window.");
doc.println("</body>");
doc.println("</html>");
doc.flush();
}
}
}