forked from cafeasp/shopifytutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIsAuthenticRequest
More file actions
37 lines (29 loc) · 1.55 KB
/
IsAuthenticRequest
File metadata and controls
37 lines (29 loc) · 1.55 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
public static bool IsAuthenticRequest(NameValueCollection querystring, string shopifySecretKey)
{
string hmac = querystring.Get("hmac");
if (string.IsNullOrEmpty(hmac))
{
return false;
}
Func<string, bool, string> replaceChars = (string s, bool isKey) =>
{
//Important: Replace % before replacing &. Else second replace will replace those %25s.
string output = (s?.Replace("%", "%25").Replace("&", "%26")) ?? "";
if (isKey)
{
output = output.Replace("=", "%3D");
}
return output;
};
var kvps = querystring.Cast<string>()
.Select(s => new { Key = replaceChars(s, true), Value = replaceChars(querystring[s], false) })
.Where(kvp => kvp.Key != "signature" && kvp.Key != "hmac")
.OrderBy(kvp => kvp.Key)
.Select(kvp => $"{kvp.Key}={kvp.Value}");
var hmacHasher = new HMACSHA256(Encoding.UTF8.GetBytes(shopifySecretKey));
var hash = hmacHasher.ComputeHash(Encoding.UTF8.GetBytes(string.Join("&", kvps)));
//Convert bytes back to string, replacing dashes, to get the final signature.
var calculatedSignature = BitConverter.ToString(hash).Replace("-", "");
//Request is valid if the calculated signature matches the signature from the querystring.
return calculatedSignature.ToUpper() == hmac.ToUpper();
}