forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebRequestUtils.cs
More file actions
326 lines (273 loc) · 11.7 KB
/
WebRequestUtils.cs
File metadata and controls
326 lines (273 loc) · 11.7 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
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
using System;
using System.Net;
using System.Text;
using ServiceStack.Text;
using ServiceStack.Logging;
#if NETFX_CORE
using System.Net.Http.Headers;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;
#endif
namespace ServiceStack
{
public class AuthenticationException : Exception
{
public AuthenticationException()
{
}
public AuthenticationException(string message)
: base(message)
{
}
public AuthenticationException(string message, Exception innerException)
: base(message, innerException)
{
}
}
// by adamfowleruk
public class AuthenticationInfo
{
private static readonly ILog Log = LogManager.GetLogger(typeof(AuthenticationInfo));
public string method { get; set; }
public string realm { get; set; }
public string qop { get; set; }
public string nonce { get; set; }
public string opaque { get; set; }
// these values used between requests, and not taken from WWW-Authenticate header of response
public string cnonce { get; set; }
public int nc { get; set; }
public AuthenticationInfo(String authHeader)
{
cnonce = "0a4f113b";
nc = 1;
// Example Digest header: WWW-Authenticate: Digest realm="testrealm@host.com", qop="auth,auth-int", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", opaque="5ccc069c403ebaf9f0171e9517f40e41"
// get method from first word
int pos = authHeader.IndexOf(" ");
if (pos < 0)
throw new AuthenticationException("Authentication header not supported: {0}".Fmt(authHeader));
method = authHeader.Substring(0, pos).ToLower();
string remainder = authHeader.Substring(pos + 1);
// split the rest by comma, then =
string[] pars = remainder.Split(',');
string[] newpars = new string[pars.Length];
int maxnewpars = 0;
// test possibility that a comma is mid value for a split (as in above example)
for (int i = 0; i < pars.Length; i++)
{
if (pars[i].EndsWith("\""))
{
newpars[maxnewpars] = pars[i];
maxnewpars++;
}
else
{
// merge with next one
newpars[maxnewpars] = pars[i] + "," + pars[i + 1];
maxnewpars++;
i++; // skips next value
}
}
// now go through each part, splitting on first = character, and removing leading and trailing spaces and " quotes
for (int i = 0; i < maxnewpars; i++)
{
int pos2 = newpars[i].IndexOf("=");
string name = newpars[i].Substring(0, pos2).Trim();
string value = newpars[i].Substring(pos2 + 1).Trim();
if (value.StartsWith("\""))
{
value = value.Substring(1);
}
if (value.EndsWith("\""))
{
value = value.Substring(0, value.Length - 1);
}
if ("qop".Equals(name))
{
qop = value;
}
else if ("realm".Equals(name))
{
realm = value;
}
else if ("nonce".Equals(name))
{
nonce = value;
}
else if ("opaque".Equals(name))
{
opaque = value;
}
}
}
public override string ToString()
{
return string.Format("[AuthenticationInfo: method={0}, realm={1}, qop={2}, nonce={3}, opaque={4}, cnonce={5}, nc={6}]", method, realm, qop, nonce, opaque, cnonce, nc);
}
}
public static class WebRequestUtils
{
private static readonly ILog Log = LogManager.GetLogger(typeof(WebRequestUtils));
internal static AuthenticationException CreateCustomException(string uri, AuthenticationException ex)
{
if (uri.StartsWith("https"))
{
return new AuthenticationException(
String.Format("Invalid remote SSL certificate, overide with: \nServicePointManager.ServerCertificateValidationCallback += ((sender, certificate, chain, sslPolicyErrors) => isValidPolicy);"),
ex);
}
return null;
}
internal static bool ShouldAuthenticate(Exception ex, string userName, string password)
{
var webEx = ex as WebException;
return (webEx != null
&& webEx.Response != null
&& ((HttpWebResponse)webEx.Response).StatusCode == HttpStatusCode.Unauthorized
&& !String.IsNullOrEmpty(userName)
&& !String.IsNullOrEmpty(password));
}
internal static void AddBasicAuth(this WebRequest client, string userName, string password)
{
client.Headers[HttpHeaders.Authorization]
= "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(userName + ":" + password));
}
#if NETFX_CORE
internal static string CalculateMD5Hash(string input)
{
var alg = HashAlgorithmProvider.OpenAlgorithm("MD5");
IBuffer buff = CryptographicBuffer.ConvertStringToBinary(input, BinaryStringEncoding.Utf8);
var hashed = alg.HashData(buff);
var res = CryptographicBuffer.EncodeToHexString(hashed);
return res.ToLower();
}
#endif
#if !(NETFX_CORE || SL5 || PCL)
internal static string CalculateMD5Hash(string input)
{
// copied/pasted by adamfowleruk
// step 1, calculate MD5 hash from input
System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);
// step 2, convert byte array to hex string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString().ToLower(); // The RFC requires the hex values are lowercase
}
#endif
internal static string padNC(int num)
{
// by adamfowleruk
var pad = "";
for (var i = 0; i < (8 - ("" + num).Length); i++)
{
pad += "0";
}
var ret = pad + num;
return ret;
}
internal static void AddAuthInfo(this WebRequest client, string userName, string password, AuthenticationInfo authInfo)
{
if ("basic".Equals(authInfo.method))
{
client.AddBasicAuth(userName, password); // FIXME AddBasicAuth ignores the server provided Realm property. Potential Bug.
}
else if ("digest".Equals(authInfo.method))
{
// do digest auth header using auth info
// auth info saved in ServiceClientBase for subsequent requests
client.AddDigestAuth(userName, password, authInfo);
}
}
internal static void AddDigestAuth(this WebRequest client, string userName, string password, AuthenticationInfo authInfo)
{
//Silverlight MD5 impl at: http://archive.msdn.microsoft.com/SilverlightMD5
#if !(SL5 || PCL)
// by adamfowleruk
// See Client Request at http://en.wikipedia.org/wiki/Digest_access_authentication
string ncUse = padNC(authInfo.nc);
authInfo.nc++; // incrememnt for subsequent requests
string ha1raw = userName + ":" + authInfo.realm + ":" + password;
string ha1 = CalculateMD5Hash(ha1raw);
string ha2raw = client.Method + ":" + client.RequestUri.PathAndQuery;
string ha2 = CalculateMD5Hash(ha2raw);
string md5rraw = ha1 + ":" + authInfo.nonce + ":" + ncUse + ":" + authInfo.cnonce + ":" + authInfo.qop + ":" + ha2;
string response = CalculateMD5Hash(md5rraw);
string header =
"Digest username=\"" + userName + "\", realm=\"" + authInfo.realm + "\", nonce=\"" + authInfo.nonce + "\", uri=\"" +
client.RequestUri.PathAndQuery + "\", cnonce=\"" + authInfo.cnonce + "\", nc=" + ncUse + ", qop=\"" + authInfo.qop + "\", response=\"" + response +
"\", opaque=\"" + authInfo.opaque + "\"";
client.Headers[HttpHeaders.Authorization] = header;
#else
throw new NotImplementedException();
#endif
}
/// <summary>
/// Naming convention for the request's Response DTO
/// </summary>
public const string ResponseDtoSuffix = "Response";
public static string GetResponseDtoName(Type requestType)
{
return requestType.FullName + ResponseDtoSuffix;
}
public static Type GetErrorResponseDtoType<TResponse>(object request)
{
var hasResponseStatus = typeof(TResponse) is IHasResponseStatus
|| typeof(TResponse).GetPropertyInfo("ResponseStatus") != null;
return hasResponseStatus ? typeof(TResponse) : GetErrorResponseDtoType(request);
}
public static Type GetErrorResponseDtoType(object request)
{
return request == null
? typeof(ErrorResponse)
: GetErrorResponseDtoType(request.GetType());
}
public static Type GetErrorResponseDtoType(Type requestType)
{
if (requestType == null)
return typeof (ErrorResponse);
//If a conventionally-named Response type exists use that regardless if it has ResponseStatus or not
var responseDtoType = AssemblyUtils.FindType(GetResponseDtoName(requestType));
if (responseDtoType == null)
{
var genericDef = requestType.GetTypeWithGenericTypeDefinitionOf(typeof(IReturn<>));
if (genericDef != null)
{
var returnDtoType = genericDef.GenericTypeArguments()[0];
var hasResponseStatus = returnDtoType is IHasResponseStatus
|| returnDtoType.GetPropertyInfo("ResponseStatus") != null;
//Only use the specified Return type if it has a ResponseStatus property
if (hasResponseStatus)
{
responseDtoType = returnDtoType;
}
}
}
return responseDtoType ?? typeof(ErrorResponse);
}
/// <summary>
/// Shortcut to get the ResponseStatus whether it's bare or inside a IHttpResult
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
public static ResponseStatus GetResponseStatus(this object response)
{
if (response == null)
return null;
var status = response as ResponseStatus;
if (status != null)
return status;
var hasResponseStatus = response as IHasResponseStatus;
if (hasResponseStatus != null)
return hasResponseStatus.ResponseStatus;
var propertyInfo = response.GetType().GetPropertyInfo("ResponseStatus");
if (propertyInfo == null)
return null;
return propertyInfo.GetProperty(response) as ResponseStatus;
}
}
}