-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathRestClient.cs
More file actions
308 lines (262 loc) · 13 KB
/
RestClient.cs
File metadata and controls
308 lines (262 loc) · 13 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
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json.Linq;
using System.Security.Cryptography;
using System.Net;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
namespace Telesign
{
/// <summary>
/// The TeleSign RestClient is a generic HTTP REST client that can be extended to make requests against any of
/// TeleSign's REST API endpoints.
///
/// See https://developer.telesign.com for detailed API documentation.
/// </summary>
public class RestClient : IDisposable
{
public static readonly string UserAgent = string.Format("TeleSignSdk/csharp-{0} .Net/{1} HttpClient",
"2.2.1",
Environment.Version.ToString());
protected string customerId;
protected string apiKey;
protected string restEndpoint;
protected HttpClient httpClient;
bool disposed = false;
/// <summary>
/// TeleSign RestClient useful for making generic RESTful requests against our API.
/// </summary>
/// <param name="customerId">Your customer_id string associated with your account.</param>
/// <param name="apiKey">Your api_key string associated with your account.</param>
/// <param name="restEndpoint">Override the default restEndpoint to target another endpoint.</param>
/// <param name="timeout">The timeout passed into HttpClient.</param>
/// <param name="proxy">The proxy passed into HttpClient.</param>
/// <param name="proxyUsername">The username passed into HttpClient.</param>
/// <param name="proxyPassword">The password passed into HttpClient.</param>
public RestClient(string customerId,
string apiKey,
string restEndpoint = "https://rest-api.telesign.com",
int timeout = 10,
WebProxy proxy = null,
string proxyUsername = null,
string proxyPassword = null)
{
this.customerId = customerId;
this.apiKey = apiKey;
this.restEndpoint = restEndpoint;
if (proxy == null)
{
this.httpClient = new HttpClient();
}
else
{
HttpClientHandler httpClientHandler = new HttpClientHandler();
httpClientHandler.Proxy = proxy;
if (proxyUsername != null && proxyPassword != null)
{
httpClientHandler.Credentials = new NetworkCredential(proxyUsername, proxyPassword);
}
this.httpClient = new HttpClient(httpClientHandler);
}
this.httpClient.Timeout = TimeSpan.FromSeconds(timeout);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
this.httpClient.Dispose();
disposed = true;
}
/// <summary>
/// A simple HTTP Response object to abstract the underlying HttpClient library response.
/// </summary>
public class TelesignResponse
{
public TelesignResponse(HttpResponseMessage response)
{
this.StatusCode = (int)response.StatusCode;
this.Headers = response.Headers;
this.Body = response.Content.ReadAsStringAsync().Result;
this.OK = response.IsSuccessStatusCode;
try
{
this.Json = JObject.Parse(this.Body);
}
catch (JsonReaderException)
{
this.Json = new JObject();
}
}
public int StatusCode { get; set; }
public HttpResponseHeaders Headers { get; set; }
public string Body { get; set; }
public JObject Json { get; set; }
public bool OK { get; set; }
}
/// <summary>
/// Generates the TeleSign REST API headers used to authenticate requests.
///
/// Creates the canonicalized stringToSign and generates the HMAC signature.This is used to authenticate requests
/// against the TeleSign REST API.
///
/// See https://developer.telesign.com/docs/authentication for detailed API documentation.
/// </summary>
/// <param name="customerId">Your account customer_id.</param>
/// <param name="apiKey">Your account api_key.</param>
/// <param name="methodName">The HTTP method name of the request as a upper case string, should be one of 'POST', 'GET', 'PUT' or 'DELETE'.</param>
/// <param name="resource">The partial resource URI to perform the request against.</param>
/// <param name="urlEncodedFields">URL encoded HTTP body to perform the HTTP request with.</param>
/// <param name="dateRfc2616">The date and time of the request formatted in rfc 2616.</param>
/// <param name="nonce">A unique cryptographic nonce for the request.</param>
/// <param name="userAgent">User Agent associated with the request.</param>
/// <param name="contentType">Content type of the request.</param>
/// <returns>A dictionary of HTTP headers to be applied to the request.</returns>
public static Dictionary<string, string> GenerateTelesignHeaders(string customerId,
string apiKey,
string methodName,
string resource,
string urlEncodedFields,
string dateRfc2616,
string nonce,
string userAgent,
string contentType = null)
{
if (dateRfc2616 == null)
{
dateRfc2616 = DateTime.UtcNow.ToString("r");
}
if (nonce == null)
{
nonce = Guid.NewGuid().ToString();
}
if (contentType == null)
{
if (methodName == "POST" || methodName == "PUT")
contentType = "application/x-www-form-urlencoded";
else
contentType = "";
}
string authMethod = "HMAC-SHA256";
StringBuilder stringToSignBuilder = new StringBuilder();
stringToSignBuilder.Append(string.Format("{0}", methodName));
stringToSignBuilder.Append(string.Format("\n{0}", contentType));
stringToSignBuilder.Append(string.Format("\n{0}", dateRfc2616));
stringToSignBuilder.Append(string.Format("\nx-ts-auth-method:{0}", authMethod));
stringToSignBuilder.Append(string.Format("\nx-ts-nonce:{0}", nonce));
if (!string.IsNullOrEmpty(contentType) && !string.IsNullOrEmpty(urlEncodedFields))
{
stringToSignBuilder.Append(string.Format("\n{0}", urlEncodedFields));
}
stringToSignBuilder.Append(string.Format("\n{0}", resource));
string stringToSign = stringToSignBuilder.ToString();
HMAC hasher = new HMACSHA256(Convert.FromBase64String(apiKey));
string signature = Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
string authorization = string.Format("TSA {0}:{1}", customerId, signature);
Dictionary<string, string> headers = new Dictionary<string, string>();
headers["Authorization"] = authorization;
headers["Date"] = dateRfc2616;
headers["Content-Type"] = contentType;
headers["x-ts-auth-method"] = authMethod;
headers["x-ts-nonce"] = nonce;
if (userAgent != null)
{
headers["User-Agent"] = userAgent;
}
return headers;
}
/// <summary>
/// Generic TeleSign REST API POST handler.
/// </summary>
/// <param name="resource">The partial resource URI to perform the request against.</param>
/// <param name="parameters">Body params to perform the POST request with.</param>
/// <returns>The TelesignResponse for the request.</returns>
public TelesignResponse Post(string resource, Dictionary<string, string> parameters)
{
return Execute(resource, HttpMethod.Post, parameters);
}
/// <summary>
/// Generic TeleSign REST API GET handler.
/// </summary>
/// <param name="resource">The partial resource URI to perform the request against.</param>
/// <param name="parameters">Body params to perform the GET request with.</param>
/// <returns>The TelesignResponse for the request.</returns>
public TelesignResponse Get(string resource, Dictionary<string, string> parameters)
{
return Execute(resource, HttpMethod.Get, parameters);
}
/// <summary>
/// Generic TeleSign REST API PUT handler.
/// </summary>
/// <param name="resource">The partial resource URI to perform the request against.</param>
/// <param name="parameters">Body params to perform the PUT request with.</param>
/// <returns>The TelesignResponse for the request.</returns>
public TelesignResponse Put(string resource, Dictionary<string, string> parameters)
{
return Execute(resource, HttpMethod.Put, parameters);
}
/// <summary>
/// Generic TeleSign REST API DELETE handler.
/// </summary>
/// <param name="resource">The partial resource URI to perform the request against.</param>
/// <param name="parameters">Body params to perform the DELETE request with.</param>
/// <returns>The TelesignResponse for the request.</returns>
public TelesignResponse Delete(string resource, Dictionary<string, string> parameters)
{
return Execute(resource, HttpMethod.Delete, parameters);
}
/// <summary>
/// Generic TeleSign REST API request handler.
/// </summary>
/// <param name="resource">The partial resource URI to perform the request against.</param>
/// <param name="method">The HTTP method name, as an upper case string.</param>
/// <param name="parameters">Params to perform the request with.</param>
/// <returns></returns>
private TelesignResponse Execute(string resource, HttpMethod method, Dictionary<string, string> parameters)
{
if (parameters == null)
{
parameters = new Dictionary<string, string>();
}
string resourceUri = string.Format("{0}{1}", this.restEndpoint, resource);
FormUrlEncodedContent formBody = new FormUrlEncodedContent(parameters);
string urlEncodedFields = formBody.ReadAsStringAsync().Result;
HttpRequestMessage request;
if (method == HttpMethod.Post || method == HttpMethod.Put)
{
request = new HttpRequestMessage(method, resourceUri);
request.Content = formBody;
}
else
{
UriBuilder resourceUriWithQuery = new UriBuilder(resourceUri);
resourceUriWithQuery.Query = urlEncodedFields;
request = new HttpRequestMessage(method, resourceUriWithQuery.ToString());
}
Dictionary<string, string> headers = GenerateTelesignHeaders(this.customerId,
this.apiKey,
method.ToString().ToUpper(),
resource,
urlEncodedFields,
null,
null,
RestClient.UserAgent);
foreach (KeyValuePair<string, string> header in headers)
{
if (header.Key == "Content-Type")
// skip Content-Type, otherwise HttpClient will complain
continue;
request.Headers.Add(header.Key, header.Value);
}
HttpResponseMessage response = this.httpClient.SendAsync(request).Result;
TelesignResponse tsResponse = new TelesignResponse(response);
return tsResponse;
}
}
}