πAuthentication
Ensuring Secure and Authenticated API Requests Using HMAC SHA256.
1. Signing an API Request
2. Step-by-Step Guide
2.1 Create the Query String from JSON
const qs = require('qs');
const jsonObj = {
field1: "value2",
nestedField: {
nestedField1: "nestedValue1"
}
};
const queryString = qs.stringify(jsonObj, { encode: false, delimiter: '&', allowDots: true });
console.log(queryString); // Output: field1=value2&nestedField.nestedField1=nestedValue1using System;
using System.Collections.Generic;
using System.Web;
using System.Text.Json;
public class Program
{
public static void Main()
{
var jsonObj = new Dictionary<string, object>
{
{ "field1", "value2" },
{ "nestedField", new Dictionary<string, object> { { "nestedField1", "nestedValue1" } } }
};
var flatDict = FlattenObject(jsonObj);
var query = HttpUtility.ParseQueryString(string.Empty);
foreach (var kvp in flatDict)
{
query[kvp.Key] = kvp.Value.ToString();
}
string queryString = query.ToString().Replace("&", "&");
Console.WriteLine(queryString); // Output: field1=value2&nestedField.nestedField1=nestedValue1
}
public static Dictionary<string, object> FlattenObject(Dictionary<string, object> obj, string parentKey = "", string sep = ".")
{
var items = new Dictionary<string, object>();
foreach (var kvp in obj)
{
var newKey = string.IsNullOrEmpty(parentKey) ? kvp.Key : $"{parentKey}{sep}{kvp.Key}";
if (kvp.Value is Dictionary<string, object> nestedDict)
{
var nestedItems = FlattenObject(nestedDict, newKey, sep);
foreach (var nestedKvp in nestedItems)
{
items[nestedKvp.Key] = nestedKvp.Value;
}
}
else
{
items[newKey] = kvp.Value;
}
}
return items;
}
}2.2 Construct the String to Sign
2.3 Sign the String using HMAC SHA256
Last updated