Last active
April 8, 2020 22:38
-
-
Save saltz/3570996e6170307a159934c5dac1a483 to your computer and use it in GitHub Desktop.
ING OpenAPI sandbox authentication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Both example certificates and key pairs have been converted to the (PKCS#12 or PFX) standard. | |
/// This simplifies the process of accessing the private keys and integrating them with the HttpClient. | |
/// This process can be done using the following openssl command: `openssl pkcs12 -export -out certificate.p12 -inkey privateKey.key -in certificate.crt` | |
/// </summary> | |
public async Task IngApiGetToken() | |
{ | |
const string clientId = "e77d776b-90af-4684-bebc-521e5b2614dd"; | |
HttpMethod method = HttpMethod.Post; | |
const string hostUrl = "https://api.sandbox.ing.com"; | |
const string path = "/oauth2/token"; | |
const string payload = "grant_type=client_credentials"; | |
string payloadDigest; | |
using (var shaProvider = new SHA256CryptoServiceProvider()) | |
{ | |
payloadDigest = Convert.ToBase64String(shaProvider.ComputeHash(Encoding.UTF8.GetBytes(payload))); | |
} | |
var digest = $"SHA-256={payloadDigest}"; | |
var date = $"{DateTime.UtcNow:ddd, dd MMM yyyy HH:mm:ss} GMT"; | |
var signingString = $"(request-target): {method.ToString().ToLower()} {path}\ndate: {date}\ndigest: {digest}"; | |
var cert = new X509Certificate2(@"singing_example.p12", "changeit"); | |
var signature = Convert.ToBase64String(cert.GetRSAPrivateKey().SignData | |
( | |
Encoding.UTF8.GetBytes(signingString), | |
HashAlgorithmName.SHA256, | |
RSASignaturePadding.Pkcs1 | |
)); | |
using (var httpClient = new HttpClient(new HttpClientHandler | |
{ | |
ClientCertificates = {new X509Certificate2(@"tls_example.p12")}, | |
ClientCertificateOptions = ClientCertificateOption.Manual | |
})) | |
{ | |
var request = new HttpRequestMessage | |
{ | |
Method = method, | |
RequestUri = new Uri($"{hostUrl}{path}"), | |
Headers = | |
{ | |
{"Accept", "application/json"}, | |
{"Digest", digest}, | |
{"Date", date}, | |
{ | |
"authorization", | |
$"Signature keyId=\"{clientId}\",algorithm=\"rsa-sha256\",headers=\"(request-target) date digest\",signature=\"{signature}\"" | |
} | |
}, | |
Content = new StringContent(payload, Encoding.UTF8, "application/x-www-form-urlencoded") | |
}; | |
var response = await httpClient.SendAsync(request); | |
var body = await response.Content.ReadAsStringAsync(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment