-
Notifications
You must be signed in to change notification settings - Fork 70
/
SharedKeyHttpMessageHandler.cs
77 lines (63 loc) · 2.73 KB
/
SharedKeyHttpMessageHandler.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
// Copyright (c) Barry Dorrans. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Globalization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
namespace idunno.Authentication.SharedKey
{
public class SharedKeyHttpMessageHandler : DelegatingHandler
{
#pragma warning disable IDE0079
#pragma warning disable IDE0290
public SharedKeyHttpMessageHandler(string keyId, byte[] key)
{
KeyId = keyId;
Key = key;
}
public SharedKeyHttpMessageHandler(string keyId, string key) : this(keyId, Convert.FromBase64String(key))
{
}
#pragma warning restore IDE0290
#pragma warning restore IDE0079
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(request);
#else
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
#endif
// Time stamp the request if it's not already timestamped so we can support expiry.
if (request.Headers.Date == null)
{
request.Headers.Date = DateTime.UtcNow;
}
// Check if we have request content, if we do then we need to add a Content-MD5 header if it doesn't already exist.
// However we can't do this if we're chunked.
if (request.Headers.TransferEncodingChunked == null || !(bool)request.Headers.TransferEncodingChunked)
{
// We can't rely on the length header, as it's not set yet.
if (request.Content != null && request.Content.Headers.ContentMD5 == null)
{
byte[] contentHash = await SignatureValidator.CalculateBodyMd5(request).ConfigureAwait(true);
if (contentHash != null && contentHash.Length != 0)
{
request.Content.Headers.ContentMD5 = contentHash;
}
}
}
byte[] hash = SharedKeySignature.Calculate(request, Key);
request.Headers.Authorization = new AuthenticationHeaderValue(
SharedKeyAuthentication.AuthorizationScheme,
string.Format(CultureInfo.InvariantCulture, "{0}:{1}", KeyId, Convert.ToBase64String(hash)));
return await base.SendAsync(request, cancellationToken).ConfigureAwait(true);
}
private string KeyId { get; set; }
private byte[] Key { get; set; }
}
}