forked from CanterburyRegionalCouncil/WebAPI.HMAC
/
HMACDelegatingHandler.cs
53 lines (44 loc) · 1.69 KB
/
HMACDelegatingHandler.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
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using WebAPI.HMAC.Crypto;
namespace WebAPI.HMAC.Http
{
public class HMACDelegatingHandler : DelegatingHandler
{
private readonly string _appId;
private readonly string _apiKey;
public HMACDelegatingHandler(string appId, string apiKey)
{
_appId = appId;
_apiKey = apiKey;
InnerHandler = new HttpClientHandler();
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// Calculate UNIX time.
var epochStart = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc);
var timeSpan = DateTime.UtcNow - epochStart;
var requestTimeStamp = Convert.ToUInt64(timeSpan.TotalSeconds).ToString();
// Create random nonce for each request
var nonce = HMACHelper.BuildNonce();
// Build the base 64 signature.
var base64Signature = HMACHelper.BuildBase64Signature(
_apiKey,
_appId,
request.RequestUri,
request.Method,
request.Content,
nonce,
requestTimeStamp
);
// Setting the values in the Authorization header using custom scheme (amx)
request.Headers.Authorization = new AuthenticationHeaderValue("amx",
$"{_appId}:{base64Signature}:{nonce}:{requestTimeStamp}");
var response = base.SendAsync(request, cancellationToken);
return response;
}
}
}