forked from eendrulat/map-and-app-gallery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.ashx
370 lines (318 loc) · 12.9 KB
/
proxy.ashx
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
<%@ WebHandler Language="C#" Class="proxy" %>
/*
| Version 10.1.1
| Copyright 2012 Esri
|
| 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.
*/
using System;
using System.IO;
using System.Web;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.Web.Caching;
//============================================================================================================================//
/// <summary>
/// Forwards requests to an ArcGIS Server REST resource. Uses information in
/// the proxy.config file to determine properties of the server.
/// </summary>
public class proxy : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
HttpRequest originalRequest = context.Request;
HttpResponse response = context.Response;
// Read config file
ProxyConfig config = ProxyConfig.GetCurrentConfig();
if(null == config)
{
HttpRuntime.Cache.Remove("authentication");
response.StatusCode = 500;
response.StatusDescription = "Proxy configuration not available; token cache cleared";
response.End();
return;
}
// Can we get the authentication spec from the cache?
AuthenticationSpec authSpec = HttpRuntime.Cache["authentication"] as AuthenticationSpec;
if (authSpec == null)
{
// No spec available--we'll have to generate one
// Post the authentication request
System.Net.HttpWebRequest authenticationReq =
(System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(config.authenticationUrl);
authenticationReq.Method = "POST";
authenticationReq.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
authenticationReq.ServicePoint.Expect100Continue = false;
string postData =
"referer=" + config.applicationURL +
"&username=" + config.username +
"&password=" + config.password +
"&expiration=" + config.tokenDurationMinutes.ToString() +
"&f=pjson";
byte[] postBytes = UTF8Encoding.UTF8.GetBytes(postData);
authenticationReq.ContentLength = postBytes.Length;
using (Stream outputStream = authenticationReq.GetRequestStream())
{
outputStream.Write(postBytes, 0, postBytes.Length);
}
// Read the authentication response
System.Net.HttpWebResponse authenticationResponse = null;
try
{
authenticationResponse = (System.Net.HttpWebResponse)authenticationReq.GetResponse();
}
catch (System.Net.WebException)
{
authenticationResponse = null;
}
if (authenticationResponse != null)
{
try
{
using (Stream byteStream = authenticationResponse.GetResponseStream())
{
System.Runtime.Serialization.Json.DataContractJsonSerializer jsonSer =
new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AuthenticationSpec));
authSpec = (AuthenticationSpec)jsonSer.ReadObject(byteStream);
}
}
catch(Exception ex)
{
authSpec = null;
}
authenticationResponse.Close();
}
// Cache the authentication
if (authSpec != null && null == authSpec.error)
{
DateTime expiresDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(authSpec.expires);
HttpRuntime.Cache.Insert("authentication", authSpec, null, expiresDate, Cache.NoSlidingExpiration);
}
else
{
response.StatusCode = 500;
response.StatusDescription = "Authentication failed";
response.End();
return;
}
}
// Check that the application's server matches the config file
string applicationURL = originalRequest.Url.Scheme + "://" + originalRequest.Url.Host;
string[] segs = originalRequest.Url.Segments;
for(int i = 0; i < (segs.Length - 1); ++i)
{
applicationURL += segs[i];
}
applicationURL = applicationURL.ToLower();
if(applicationURL.EndsWith("/")) applicationURL = applicationURL.Substring(0, applicationURL.Length - 1);
string configAppURL = config.applicationURL.ToLower();
if (configAppURL.EndsWith("/")) configAppURL = configAppURL.Substring(0, configAppURL.Length - 1);
if (applicationURL != configAppURL)
{
response.StatusCode = 500;
response.StatusDescription = "Unsupported application URL";
response.End();
return;
}
// Get the URL requested by the client (take the entire querystring at once to handle the case of the
// URL itself containing querystring parameters); lop off initial question mark of query string
string dataURL = 1 < originalRequest.Url.Query.Length ? originalRequest.Url.Query.Substring(1) : "";
// Check that the data URL matches the config file
string lowerDataURL = dataURL.ToLower();
if (!lowerDataURL.StartsWith(config.dataUrlPrefix.ToLower()))
{
response.StatusCode = 500;
response.StatusDescription = "Unsupported data URL";
response.End();
return;
}
// Switch to SSL if desired by authentication response
else if (authSpec.ssl && 5 < lowerDataURL.Length && lowerDataURL.StartsWith("http:"))
{
dataURL = "https:" + dataURL.Substring(5);
}
// Create the proxied URL
if (dataURL.Contains("?"))
dataURL += "&token=" + authSpec.token;
else
dataURL += "?token=" + authSpec.token;
// Set up the user request
System.Net.HttpWebRequest proxiedReq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(dataURL);
proxiedReq.Method = context.Request.HttpMethod;
proxiedReq.ServicePoint.Expect100Continue = false;
// Set body of request for POST requests
if (context.Request.InputStream.Length > 0)
{
byte[] bytes = new byte[context.Request.InputStream.Length];
context.Request.InputStream.Read(bytes, 0, (int)context.Request.InputStream.Length);
proxiedReq.ContentLength = bytes.Length;
string ctype = context.Request.ContentType;
if (String.IsNullOrEmpty(ctype)) {
proxiedReq.ContentType = "application/x-www-form-urlencoded";
}
else {
proxiedReq.ContentType = ctype;
}
using (Stream outputStream = proxiedReq.GetRequestStream())
{
outputStream.Write(bytes, 0, bytes.Length);
}
}
// Send the user request to the server
System.Net.HttpWebResponse serverResponse = null;
try
{
serverResponse = (System.Net.HttpWebResponse)proxiedReq.GetResponse();
}
catch (System.Net.WebException webExc)
{
response.StatusCode = 500;
response.StatusDescription = webExc.Status.ToString();
response.Write(webExc.Message);
response.Write("<br />");
response.Write(webExc.Response);
response.End();
return;
}
// Set up the response to the client
if (serverResponse != null)
{
response.ContentType = serverResponse.ContentType;
try
{
using (Stream byteStream = serverResponse.GetResponseStream())
{
// Text response
if (serverResponse.ContentType.Contains("text") ||
serverResponse.ContentType.Contains("json"))
{
using (StreamReader sr = new StreamReader(byteStream))
{
string strResponse = sr.ReadToEnd();
response.Write(strResponse);
}
}
else
{
// Binary response (image, lyr file, other binary file)
BinaryReader br = new BinaryReader(byteStream);
// If the server provides the Content Length, use it.
// But just because the value is zero doesn't mean that the server
// didn't send us anything; cf ArcGIS.com & item thumbnails.
int numBytes = (int)serverResponse.ContentLength;
if (0 >= numBytes) numBytes = 4096;
// Read until the response is empty
int bytesRead = 0;
do
{
byte[] outb = br.ReadBytes(numBytes);
bytesRead = outb.Length;
// Send the image to the client
if (0 < bytesRead) response.OutputStream.Write(outb, 0, bytesRead);
} while (0 < bytesRead);
br.Close();
}
}
}
catch (Exception ex)
{
response.StatusCode = 500;
response.StatusDescription = ex.Message.ToString();
response.Write(ex.Message);
}
serverResponse.Close();
}
response.End();
}
public bool IsReusable
{
get {
return false;
}
}
}
//============================================================================================================================//
/// <summary>
/// Represents the contents of the config file and provides routines for accessing those contents.
/// </summary>
[XmlRoot("ProxyConfig")]
public class ProxyConfig
{
#region Static Members
private static object _lockobject = new object();
public static ProxyConfig LoadProxyConfig(string fileName)
{
ProxyConfig config = null;
lock (_lockobject)
{
if (System.IO.File.Exists(fileName))
{
XmlSerializer reader = new XmlSerializer(typeof(ProxyConfig));
using (System.IO.StreamReader file = new System.IO.StreamReader(fileName))
{
config = (ProxyConfig)reader.Deserialize(file);
}
}
}
return config;
}
public static ProxyConfig GetCurrentConfig()
{
ProxyConfig config = HttpRuntime.Cache["proxyConfig"] as ProxyConfig;
if (config == null)
{
string fileName = GetFilename(HttpContext.Current);
config = LoadProxyConfig(fileName);
if (config != null)
{
CacheDependency dep = new CacheDependency(fileName);
HttpRuntime.Cache.Insert("proxyConfig", config, dep);
}
}
return config;
}
public static string GetFilename(HttpContext context)
{
return context.Server.MapPath("~/proxy.config");
}
#endregion
[XmlElement("applicationURL")]
public string applicationURL;
[XmlElement("authenticationUrl")]
public string authenticationUrl;
[XmlElement("dataUrlPrefix")]
public string dataUrlPrefix;
[XmlElement("username")]
public string username;
[XmlElement("password")]
public string password;
[XmlElement("tokenDurationMinutes")]
public int tokenDurationMinutes;
}
//============================================================================================================================//
/// <summary>
/// Represents the contents of the authentication specification returned from arcgis.com.
/// </summary>
[System.Runtime.Serialization.DataContract]
public class AuthenticationSpec
{
[System.Runtime.Serialization.DataMember]
public string token;
[System.Runtime.Serialization.DataMember]
public long expires;
[System.Runtime.Serialization.DataMember]
public bool ssl;
[System.Runtime.Serialization.DataMember]
public object error;
}