forked from Vonage/vonage-dotnet-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ApiRequest.cs
511 lines (471 loc) · 23.7 KB
/
ApiRequest.cs
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
using Newtonsoft.Json;
using Nexmo.Api.Cryptography;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using Microsoft.Extensions.Logging;
namespace Nexmo.Api.Request
{
/// <summary>
/// Responsible for sending all Nexmo API requests that do not make use of Application authentication.
/// For application authentication, see VersionedApiRequest.
/// </summary>
public static class ApiRequest
{
public enum AuthType
{
Basic,
Bearer,
Query
}
public enum UriType
{
Api,
Rest
}
const string LOGGER_CATEGORY = "Nexmo.Api.Request.ApiRequest";
private static string _userAgent;
/// <summary>
/// Sets the user agent for an HTTP request
/// </summary>
/// <param name="request"></param>
/// <param name="creds"></param>
internal static void SetUserAgent(ref HttpRequestMessage request, Credentials creds)
{
if (string.IsNullOrEmpty(_userAgent))
{
#if NETSTANDARD1_6 || NETSTANDARD2_0 || NETSTANDARD2_1
// TODO: watch the next core release; may have functionality to make this cleaner
var languageVersion = (System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription)
.Replace(" ", "")
.Replace("/", "")
.Replace(":", "")
.Replace(";", "")
.Replace("_", "")
.Replace("(", "")
.Replace(")", "")
;
#else
var languageVersion = System.Diagnostics.FileVersionInfo
.GetVersionInfo(typeof(int).Assembly.Location)
.ProductVersion;
#endif
var libraryVersion = typeof(ApiRequest)
.GetTypeInfo()
.Assembly
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
.InformationalVersion;
_userAgent = $"nexmo-dotnet/{libraryVersion} dotnet/{languageVersion}";
var appVersion = creds?.AppUserAgent ?? Configuration.Instance.Settings["appSettings:Nexmo.UserAgent"];
if (!string.IsNullOrWhiteSpace(appVersion))
{
_userAgent += $" {appVersion}";
}
}
request.Headers.UserAgent.ParseAdd(_userAgent);
}
/// <summary>
/// Builds a query string for a get request - if there is a security secret a signature is built for the request and added to the query string
/// </summary>
/// <param name="parameters"></param>
/// <param name="creds"></param>
/// <returns></returns>
private static StringBuilder BuildQueryString(IDictionary<string, string> parameters, Credentials creds = null)
{
var apiKey = (creds?.ApiKey ?? Configuration.Instance.Settings["appSettings:Nexmo.api_key"])?.ToLower();
var apiSecret = creds?.ApiSecret ?? Configuration.Instance.Settings["appSettings:Nexmo.api_secret"];
var securitySecret = creds?.SecuritySecret ?? Configuration.Instance.Settings["appSettings:Nexmo.security_secret"];
SmsSignatureGenerator.Method method;
if (creds?.Method != null)
{
method = creds.Method;
}
else if(Enum.TryParse(Configuration.Instance.Settings["appSettings:Nexmo.signing_method"], out method))
{
//left blank intentionally
}
else
{
method = SmsSignatureGenerator.Method.md5hash;
}
var sb = new StringBuilder();
var signature_sb = new StringBuilder();
Action<IDictionary<string, string>, StringBuilder> buildStringFromParams = (param, strings) =>
{
foreach (var kvp in param)
{
//Special Case for ids from MessagesSearch API which needs a sereies of ID's with unescaped &/=
if(kvp.Key == "ids")
{
strings.AppendFormat("{0}={1}&", WebUtility.UrlEncode(kvp.Key), kvp.Value);
}
else
{
strings.AppendFormat("{0}={1}&", WebUtility.UrlEncode(kvp.Key), WebUtility.UrlEncode(kvp.Value));
}
}
};
Action<IDictionary<string, string>, StringBuilder> buildSignatureStringFromParams = (param, strings) =>
{
foreach (var kvp in param)
{
strings.AppendFormat("{0}={1}&", kvp.Key.Replace('=','_').Replace('&','_'), kvp.Value.Replace('=', '_').Replace('&', '_'));
}
};
parameters.Add("api_key", apiKey);
if (string.IsNullOrEmpty(securitySecret))
{
// security secret not provided, do not sign
parameters.Add("api_secret", apiSecret);
buildStringFromParams(parameters, sb);
return sb;
}
parameters.Add("timestamp", ((int)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds).ToString(CultureInfo.InvariantCulture));
var sortedParams = new SortedDictionary<string, string>(parameters);
buildStringFromParams(sortedParams, sb);
buildSignatureStringFromParams(sortedParams, signature_sb);
var queryToSign = "&" + signature_sb.ToString();
queryToSign = queryToSign.Remove(queryToSign.Length - 1);
var signature = SmsSignatureGenerator.GenerateSignature(queryToSign, securitySecret, method);
sb.AppendFormat("sig={0}", signature);
return sb;
}
/// <summary>
/// extracts parameters from an object into a dictionary
/// </summary>
/// <param name="parameters"></param>
/// <returns></returns>
internal static Dictionary<string, string> GetParameters(object parameters)
{
var json = JsonConvert.SerializeObject(parameters,
Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
return JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
}
/// <summary>
/// Retrieves the Base URI for a given component and appends the given url to the end of it.
/// </summary>
/// <param name="component"></param>
/// <param name="url"></param>
/// <returns></returns>
internal static Uri GetBaseUriFor(Type component, string url = null)
{
Uri baseUri;
if (typeof(NumberVerify) == component
|| typeof(ApiSecret) == component
|| typeof(ApplicationV2) == component
|| typeof(Voice.Call) == component
|| typeof(Redact) == component)
{
baseUri = new Uri(Configuration.Instance.Settings["appSettings:Nexmo.Url.Api"]);
}
else
{
baseUri = new Uri(Configuration.Instance.Settings["appSettings:Nexmo.Url.Rest"]);
}
return string.IsNullOrEmpty(url) ? baseUri : new Uri(baseUri, url);
}
public static Uri GetBaseUri(UriType uriType, string url = null)
{
Uri baseUri;
switch (uriType)
{
case UriType.Api:
baseUri = new Uri(Configuration.Instance.Settings["appSettings:Nexmo.Url.Api"]);
break;
case UriType.Rest:
baseUri = new Uri(Configuration.Instance.Settings["appSettings:Nexmo.Url.Rest"]);
break;
default:
throw new Exception("Unknown Uri Type Detected");
}
return string.IsNullOrEmpty(url) ? baseUri : new Uri(baseUri, url);
}
/// <summary>
/// Creates a query string for the given parameters - if the auth type is Query the credentials are appended to the end of the query string
/// </summary>
/// <param name="parameters"></param>
/// <param name="type"></param>
/// <param name="creds"></param>
/// <returns></returns>
internal static StringBuilder GetQueryStringBuilderFor(object parameters, AuthType type, Credentials creds = null)
{
Dictionary<string, string> apiParams;
if(!(parameters is Dictionary<string,string>))
{
apiParams = GetParameters(parameters);
}
else
{
apiParams = (Dictionary<string, string>)parameters;
}
var sb = new StringBuilder();
if (type == AuthType.Query)
{
sb = BuildQueryString(apiParams, creds);
}
else
{
foreach (var key in apiParams.Keys)
{
sb.AppendFormat("{0}={1}&", WebUtility.UrlEncode(key), WebUtility.UrlEncode(apiParams[key]));
}
}
return sb;
}
/// <summary>
/// Send a GET request to the versioned Nexmo API.
/// Do not include credentials in the parameters object. If you need to override credentials, use the optional Credentials parameter.
/// </summary>
/// <param name="uri">The URI to GET</param>
/// <param name="parameters">Parameters required by the endpoint (do not include credentials)</param>
/// <param name="credentials">(Optional) Overridden credentials for only this request</param>
/// <exception cref="NexmoHttpRequestException">Thrown if the API encounters a non-zero result</exception>
public static T DoGetRequestWithQueryParameters<T>(Uri uri, AuthType authType, object parameters = null, Credentials credentials = null)
{
if (parameters == null)
parameters = new Dictionary<string, string>();
var sb = GetQueryStringBuilderFor(parameters, authType, credentials);
var requestUri = new Uri(uri + (sb.Length != 0 ? "?" + sb : ""));
return SendGetRequest<T>(requestUri, authType, credentials);
}
/// <summary>
/// Sends an HTTP GET request to the Nexmo API without any additional parameters
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="uri"></param>
/// <param name="authType"></param>
/// <param name="creds"></param>
/// <exception cref="NexmoHttpRequestException">Thrown if the API encounters a non-zero result</exception>
private static T SendGetRequest<T>(Uri uri, AuthType authType, Credentials creds)
{
var logger = Logger.LogProvider.GetLogger(LOGGER_CATEGORY);
var appId = creds?.ApplicationId ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Id"];
var appKeyPath = creds?.ApplicationKey ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Key"];
var apiKey = (creds?.ApiKey ?? Configuration.Instance.Settings["appSettings:Nexmo.api_key"])?.ToLower();
var apiSecret = creds?.ApiSecret ?? Configuration.Instance.Settings["appSettings:Nexmo.api_secret"];
var req = new HttpRequestMessage
{
RequestUri = uri,
Method = HttpMethod.Get
};
SetUserAgent(ref req, creds);
if (authType == AuthType.Basic)
{
var authBytes = Encoding.UTF8.GetBytes(apiKey + ":" + apiSecret);
req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic",
Convert.ToBase64String(authBytes));
}
else if (authType == AuthType.Bearer)
{
req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer",
Jwt.CreateToken(appId, appKeyPath));
}
logger.LogDebug($"GET {uri}");
var json = SendHttpRequest(req).JsonResponse;
return JsonConvert.DeserializeObject<T>(json);
}
/// <summary>
/// Send a request to the Nexmo API using the specified HTTP method and the provided parameters.
/// Do not include credentials in the parameters object. If you need to override credentials, use the optional Credentials parameter.
/// </summary>
/// <param name="method">HTTP method (POST, PUT, DELETE, etc)</param>
/// <param name="uri">The URI to communicate with</param>
/// <param name="parameters">Parameters required by the endpoint (do not include credentials)</param>
/// <param name="creds">(Optional) Overridden credentials for only this request</param>
/// <exception cref="NexmoHttpRequestException">thrown if an error is encountered when talking to the API</exception>
/// <returns></returns>
public static NexmoResponse DoRequestWithUrlContent(string method, Uri uri, Dictionary<string, string> parameters, AuthType authType = AuthType.Query, Credentials creds = null)
{
var logger = Logger.LogProvider.GetLogger(LOGGER_CATEGORY);
var sb = new StringBuilder();
// if parameters is null, assume that key and secret have been taken care of
if (null != parameters)
{
sb = GetQueryStringBuilderFor(parameters, authType, creds);
}
var req = new HttpRequestMessage
{
RequestUri = uri,
Method = new HttpMethod(method)
};
if (authType == AuthType.Basic)
{
var apiKey = (creds?.ApiKey ?? Configuration.Instance.Settings["appSettings:Nexmo.api_key"])?.ToLower();
var apiSecret = creds?.ApiSecret ?? Configuration.Instance.Settings["appSettings:Nexmo.api_secret"];
var authBytes = Encoding.UTF8.GetBytes(apiKey + ":" + apiSecret);
req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic",
Convert.ToBase64String(authBytes));
}
SetUserAgent(ref req, creds);
var data = Encoding.ASCII.GetBytes(sb.ToString());
req.Content = new ByteArrayContent(data);
req.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
logger.LogDebug($"{method} {uri} {sb}");
return SendHttpRequest(req);
}
/// <summary>
/// Sends an HttpRequest on to the Nexmo API
/// </summary>
/// <param name="req"></param>
/// <exception cref="NexmoHttpRequestException">thrown if an error is encountered when talking to the API</exception>
/// <returns></returns>
public static NexmoResponse SendHttpRequest(HttpRequestMessage req)
{
var logger = Logger.LogProvider.GetLogger(LOGGER_CATEGORY);
var response = Configuration.Instance.Client.SendAsync(req).Result;
var stream = response.Content.ReadAsStreamAsync().Result;
string json;
using (var sr = new StreamReader(stream))
{
json = sr.ReadToEnd();
}
try
{
logger.LogDebug(json);
response.EnsureSuccessStatusCode();
return new NexmoResponse
{
Status = response.StatusCode,
JsonResponse = json
};
}
catch (HttpRequestException exception)
{
logger.LogError($"FAIL: {response.StatusCode}");
throw new NexmoHttpRequestException(exception.Message + " Json from error: " + json) { HttpStatusCode = response.StatusCode, Json = json };
}
}
/// <summary>
/// Send a request to the versioned Nexmo API.
/// Do not include credentials in the parameters object. If you need to override credentials, use the optional Credentials parameter.
/// </summary>
/// <param name="method">HTTP method (POST, PUT, DELETE, etc)</param>
/// <param name="uri">The URI to communicate with</param>
/// <param name="payload">Parameters required by the endpoint (do not include credentials)</param>
/// <param name="authType">Authorization type used on the API</param>
/// <param name="creds">(Optional) Overridden credentials for only this request</param>
/// <exception cref="NexmoHttpRequestException">thrown if an error is encountered when talking to the API</exception>
public static T DoRequestWithJsonContent<T>(string method, Uri uri, object payload, AuthType authType, Credentials creds)
{
var appId = creds?.ApplicationId ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Id"];
var appKeyPath = creds?.ApplicationKey ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Key"];
var apiKey = (creds?.ApiKey ?? Configuration.Instance.Settings["appSettings:Nexmo.api_key"])?.ToLower();
var apiSecret = creds?.ApiSecret ?? Configuration.Instance.Settings["appSettings:Nexmo.api_secret"];
var logger = Logger.LogProvider.GetLogger(LOGGER_CATEGORY);
var req = new HttpRequestMessage
{
RequestUri = uri,
Method = new HttpMethod(method),
};
SetUserAgent(ref req, creds);
if (authType == AuthType.Basic)
{
var authBytes = Encoding.UTF8.GetBytes(apiKey + ":" + apiSecret);
req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic",
Convert.ToBase64String(authBytes));
}
else if (authType == AuthType.Bearer)
{
// attempt bearer token auth
req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer",
Jwt.CreateToken(appId, appKeyPath));
}
else if (authType == AuthType.Query)
{
var sb = BuildQueryString(new Dictionary<string, string>(), creds);
req.RequestUri = new Uri(uri + (sb.Length != 0 ? "?" + sb : ""));
}
else
{
throw new ArgumentException("Unkown Auth Type set for function");
}
var json = JsonConvert.SerializeObject(payload,
Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
logger.LogDebug($"Request URI: {uri}");
logger.LogDebug($"JSON Payload: {json}");
var data = Encoding.UTF8.GetBytes(json);
req.Content = new ByteArrayContent(data);
req.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
var json_response = SendHttpRequest(req).JsonResponse;
return JsonConvert.DeserializeObject<T>(json_response);
}
/// <summary>
/// Sends a GET request to the Nexmo API using a JWT and returns the full HTTP resonse message
/// this is primarily for pulling a raw stream off an API call -e.g. a recording
/// </summary>
/// <param name="uri"></param>
/// <param name="creds"></param>
/// <returns>HttpResponseMessage</returns>
/// <exception cref="NexmoHttpRequestException">thrown if an error is encountered when talking to the API</exception>
public static HttpResponseMessage DoGetRequestWithJwt(Uri uri, Credentials creds)
{
var logger = Logger.LogProvider.GetLogger(LOGGER_CATEGORY);
var appId = creds?.ApplicationId ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Id"];
var appKeyPath = creds?.ApplicationKey ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Key"];
var req = new HttpRequestMessage
{
RequestUri = uri,
Method = HttpMethod.Get
};
SetUserAgent(ref req, creds);
req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer",
Jwt.CreateToken(appId, appKeyPath));
logger.LogDebug($"GET {uri}");
var result = Configuration.Instance.Client.SendAsync(req).Result;
try
{
result.EnsureSuccessStatusCode();
return result;
}
catch (HttpRequestException ex)
{
logger.LogError($"FAIL: {result.StatusCode}");
throw new NexmoHttpRequestException(ex.Message, ex) { HttpStatusCode = result.StatusCode };
}
}
/// <summary>
/// Sends a Post request to the specified endpoint with the given parameters
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="uri"></param>
/// <param name="parameters"></param>
/// <param name="creds"></param>
/// <returns></returns>
/// <exception cref="NexmoHttpRequestException">thrown if an error is encountered when talking to the API</exception>
public static T DoPostRequestUrlContentFromObject<T>(Uri uri, object parameters, Credentials creds = null)
{
var apiParams = GetParameters(parameters);
return DoPostRequestWithUrlContent<T>(uri, apiParams, creds);
}
/// <summary>
/// Send a Post Request with Url Content
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="uri"></param>
/// <param name="parameters"></param>
/// <param name="creds"></param>
/// <returns></returns>
/// <exception cref="NexmoHttpRequestException">thrown if an error is encountered when talking to the API</exception>
public static T DoPostRequestWithUrlContent<T>(Uri uri, Dictionary<string, string> parameters, Credentials creds = null)
{
var response = DoRequestWithUrlContent("POST", uri, parameters, creds:creds);
return JsonConvert.DeserializeObject<T>(response.JsonResponse);
}
/// <summary>
/// Sends an HTTP DELETE
/// </summary>
/// <param name="uri"></param>
/// <param name="parameters"></param>
/// <param name="creds"></param>
/// <returns></returns>
/// <exception cref="NexmoHttpRequestException">thrown if an error is encountered when talking to the API</exception>
public static NexmoResponse DoDeleteRequestWithUrlContent(Uri uri, Dictionary<string, string> parameters, AuthType authType = AuthType.Query, Credentials creds = null) => DoRequestWithUrlContent("DELETE", uri, parameters, authType, creds);
}
}